Mybatis学习笔记(四)动态sql

一、if

对于该标签,当test的值为true时,会将其包含的SQL片段拼接到其所在的SQL语句中

语法:<if test="条件">sql语句部分</if>

案例:

接口方法

List<Student> selectStudentIf(Student student);

mapper文件

<select id="selectStudentIf" resultType="com.demo.domain.Student">

select id,name,age,email from student
where
<if test="name != null and name != '' ">
name = #{name}
</if>
<if test="age > 0">
and age = #{age}
</if>

</select>

如果以上if条件全部成立,则等价于

<select id="selectStudentIf" resultType="com.demo.domain.Student">

select id,name,age,email from student
where name = #{name} and age = #{age}

</select>

但是这种写法有一个缺陷,当name的条件不成立时,拼接就会有错误

<select id="selectStudentIf" resultType="com.demo.domain.Student">

select id,name,age,email from student
where and age = #{age}  <!-- 错误! -->

</select>

这种情况我们可以用<where>解决

二、where

<where>用来包含多个<if>,当多个if有一个成立时,<where>会自动增加一个where关键字,并去掉if中多余的and,or等。

接口方法

List<Student> selectStudentWhere(Student student);

mapper文件

<select id="selectStudentWhere" resultType="com.demo.domain.Student">

select id,name,age,email from student
<where>
<if test="name != null and name != '' ">
name = #{name}
</if>
<if test="age > 0">
and age = #{age}
</if>
</where>

</select>

无论name处的条件是否成立,都不会出现多余的"and"造成sql语句的错误

三、foreach

<foreach/>标签用于实现对于数组和集合的遍历,主要用在sql的in语句中。

1.collection表示要遍历的集合类型,list、array等

2.open、close、separator为对遍历内容的SQL拼接

语法:

<foreach collection="集合类型" open="开始的字符" close="结束的字符"

item="集合中的成员" separato="集合成员之间的分隔符">

</foreach>

接口

List<Student> selectStudentForeach(List<Student> stulist);

mapper文件

<select id="selectStudentForeach" resultType="com.demo.domain.Student">

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

</select>

以上等价于

<select id="selectStudentForeach" resultType="com.demo.domain.Student">

select * from student where id in (id1,id2,id3...)

</select>

四、代码片段

<sql/>标签用于定义SQL片段,以使其它SQL标签复用。而其它标签使用该SQL片段,需要使用<include/>子标签。该<sql/>标签可以定义SQL语句中的任何部分。所以<include/>子标签可以放在动态SQL的任何位置。

接口方法

List<Student> selectStudentSqlFragment(List<Student> stuList);

mapper文件 

<sql id="studentSQL">
id,name.age,email
</sql>

<select id="selectStudentSqlFragment" resultType="com.demo.domain.Student">

select <include refid="studentSQL" /> from student
<where>
<if test="name != null and name != '' ">
name = #{name}
</if>
<if test="age > 0">
and age = #{age}
</if>
</where>

</select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值