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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值