Mybatis动态SQL

MyBatis的动态SQL是其强大特性之一,简化了条件拼接SQL的复杂性。本文介绍了常用的动态SQL元素,如if、where、foreach、choose(when otherwise)、set和bind,以及SQL片段抽取,帮助开发者更高效地编写和管理SQL语句。
摘要由CSDN通过智能技术生成

动态 SQL 是 MyBatis 的强大特性之一。你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦

常用的动态SQL元素:

if
where
foeach
choose(when otherwise)
set
bing

一、if

根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果没有则执行失败,这里注意个小细节,id为int数据类型不能用null来表示,一般配合where元素一起使用

<select id="findByCondition" parameterType="student" resultType="student">
    select * from student where
        <if test="id!=0">
            id=#{id}
        </if>
</select>

二、where

where元素,可以很容易解决上面的问题,只需要简单的修改,并且可以进行多个条件过滤判断,若最后的 内容是“and”或“or”开头,where元素也知道如何将他们去除

<select id="findByCondition" parameterType="student" resultType="student">,
    select * from student
    <where>
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="name!=null">
            and name=#{naem}
        </if>
    </where>
</select>

三、foreach

执行sql的拼接操作,foreach元素非常强大的,允许指定一个集合,声明可以用在元素体内的集合项和索引变量
属性
collection:参数容器类型, (list-集合, array-数组)。
open:开始的 SQL 语句。
close:结束的 SQL 语句。
item:参数变量名。
separator:分隔符。

<select id="findByIds" parameterType="list" resultType="student">
    select * from student
    <where>
        <foreach  item="id" collection="array" open="id in(" close=")" separator=",">
            #{id}
        </foreach>
    </where>
</select>

四、whoose(when otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句
传入了 “id” 就按 “id” 查找,传入了 “name” 就按 “name” 查找的情形。若两者都没有传入,就返回sex = '男’的条件查询

<select id="findByIds" parameterType="hasmap" resultType="student">
    select * from student where
    <whoose>
        <when thes="id!=0">
       	 and id=#{id}
        </when>
        <when test="name!=null">
            and name=#{naem}
        </when>
         <otherwise>
     		 AND sex = '男'
    </otherwise>
    </whoose>
</select>

五、set

set 元素可以用于动态包含需要更新的列(也就是匹配到的if元素),忽略其它不更新的列

<update id="updateById">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
    </set>
  where id=#{id}
</update>

五、bind

允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文,例如模糊查询:

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

六、SQL片段抽取

Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

<!--抽取sql片段简化编写-->
<sql id="selectStudent" select * from student</sql>
<select id="findById" parameterType="int" resultType="student">
    <include refid="selectStudent"></include> where id=#{id}
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值