MyBatis中xml文件动态SQL

来源于 java技术 公众号

MyBatis中xml文件动态SQL

if标签
set标签
trim标签
choose标签
foreach标签
SQL片段

逐个分析

if标签

<select id="queryBlogIf" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <if test="title != null">
   title = #{title}
  </if>
  <if test="author != null">
   and author = #{author}
  </if>
 </where>
</select>

注意
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

可以用trim标签替换该代码

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

trim标签

prefix trim标签内sql语句加前缀
suffix trim标签内sql语句加后缀
prefixOverrides trim标签内sql语句去除多余的前缀
suffixOverrides trim标签内sql语句去除多余的后缀

set标签

<update id="updateBlog" parameterType="map">
 update blog
 <set>
  <if test="title != null">
   title = #{title},
  </if>
  <if test="author != null">
   author = #{author}
  </if>
 </set>
 where id = #{id};
</update>

注意:set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)

使用trim标签

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

choose标签

choose:1、when 2、otherwise

<select id="queryBlogChoose" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <choose>
   <when test="title != null">
    title = #{title}
   </when>
   <when test="author != null">
    and author = #{author}
   </when>
   <otherwise>
    and views = #{views}
   </otherwise>
  </choose>
 </where>
</select>

foreach标签

<select id="queryBlogForeach" parameterType="map" resultType="blog">
 select * from blog
 <where>
	1=1 
  <!--
  collection:指定输入对象中的集合属性
  item:每次遍历生成的对象
  open:开始遍历时的拼接字符串
  close:结束时拼接的字符串
  separator:遍历对象之间需要拼接的字符串
  select * from blog where 1=1 and (id=1 or id=2 or id=3)
  -->
  <foreach collection="ids" item="id" open="and (" close=")"
  separator=" or ">
   id=#{id}
  </foreach>
 </where>
</select>

SQL片段

<sql id="if-title-author">
 <if test="title != null">
  title = #{title}
 </if>
 <if test="author != null">
  and author = #{author}
 </if>
</sql>

引用SQL片段

<select id="queryBlogIf" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace-->
  <include refid="if-title-author"></include>
  <!-- 在这里还可以引用其他的 sql 片段 -->
 </where>
</select>

注意:最好基于 单表来定义 sql 片段,提高片段的可重用性
在 sql 片段中不要包括 where


版权声明:本文为weixin_47792333原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。