MyBatis封装了JDBC通过Mapper代理的方式,以前繁琐的操作通过“属性与字段映射”就简单化解。
一、动态Sql
Sql语句会随着用户的输入或者外部条件的变化而变化,则称之为动态Sql
1、if和where
因为采用了Mapper代理开发,我们可以通过写xml的形式来编写我们的SQL,在原有的Mapper文件里我们进行如下改造,使得sql语句可以实现的功能更加多样化,以适应平时业务中的各种情况
<select id="selByCondition" resultMap="rm">
select *
from mybatis
<where>
<if test="status !=null">
and STATUS=#{STATUS}
</if>
<if test="companyName !=null and companyName !=''">
and company_name like #{companyName}
</if>
<if test="bracdName !=null and bracdName !=''">
and bracd_name like #{bracdName}
</if>
</where>
</select>
where
标签可以自动帮我们去掉and或者or,这样,不管查询的条件怎么变,跟着这个逻辑流程走就不会出现SQL语法毛病而导致查询不出来的毛病啦,因为null的情况已经被if所过滤掉了
2.choose-when-ortherwise
对于从多个条件中选择一个的单条件查询的场景,利用分支嵌套就可以实现动态选择单条件:
在MyBatis的Mapper代理中,choose
相当于switch,when
相当于case
<select id="selByCondition2" resultMap="rm">
select *
from mybatis where
<choose>
<when test="status !=null">
STATUS=#{STATUS}
</when>
<when test="companyName !=null and companyName !=''">
company_name like #{companyName}
</when>
<when test="bracdName !=null and bracdName !=''">
bracd_name like #{bracdName}
</when>
<otherwise>1=1</otherwise>
</choose>
</select>
与多条件查询不同的是,SQL语句中只会有一个分支生效
3.foreach
对于批量删除的场景,传统的方法是通过in关键字结合占位符来确定
where id in (?,?,?)
所以使用了@Param
注解改变了map集合中默认的key
void deleteById(@Param("ids") int[] id);
于是MyBatis中的<foreach>
解决了这一麻烦:
本质是通过遍历的形式,批量删除的数据是由id数组或者集合来决定,collection
属性决定了要遍历哪个数组/集合,item属性则来存放选出的元素,并把它放在占位符里,separator
属性表示分隔符
<delete id="deleteById">
delete frpm mybatis where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>;
</delete>