一、动态SQL
1.概述
-
动态SQL: 是 MyBatis 的强大特性之一,解决拼接动态SQL时候的难题,提高开发效率
-
分类
-
if
-
choose(when,otherwise)
-
trim(where,set)
-
foreach
2.if
3.choose、when、otherwise
4.trim、where、set
4.1trim
-
trim : 用于去掉或者添加标签中的内容
-
prefix:可以在 trim 标签内容前面添加内容
-
prefixOverrides:可以覆盖前面的某些内容
-
suffix:在 trim 标签后面添加内容
-
suffixOverrides:去掉 trim 标签内容最后面的值
4.2where
-
where 后面直接跟 if
-
age null
-
使用了 where 标签之后,解决了这些问题
4.3set
-
set:
set
元素可以用于动态包含需要更新的列
-
mapper.xml
<update id="updateSet">
update student
<set>
<if test="name != null">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</update>
void updateSet(@Param("age") Integer age,@Param("name")String name
,@Param("clsId") Long clsId,@Param("id")Long id);
5.foreach
-
foreach
:
用于对集合遍历。
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
-
查询 id 在 1,3,4 之间的学生信息
-
mapper.xml
<select id="selectForeach" resultType="cn.sycoder.domain.Student">
select * from student
<where>
<foreach collection="ids" item="id" index="i" open="id in(" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
List<Student> selectForeach(@Param("ids") List<Long> ids);
-
collection:传参的数组集合
-
item:遍历拿到的每一个元素
-
index:索引
-
open : foreach 标签内容的开始符
-
close : foreach 标签内容的结束符
-
separator:分隔符
-
取值取的就是 item 的元素值
-
注意:当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
6.script
-
script:
要在带
注解的映射器接口类
中使用动态 SQL,可以使用
script
元素。
-
使用注解操作 mybatis
-
需求:查询所有的学生信息,用注解方式实现
@Select("select * from student")
List<Student> selectAll();
-
更新学生信息,使用 script 标签
@Update({
"<script>",
"update student",
" <set>",
" <if test='name != null'>name=#{name},</if>",
" <if test='age != null'>age=#{age},</if>",
" <if test='clsId != null'>class_id=#{clsId},</if>",
" </set>",
"where id=#{id}",
"</script>"
})
void updateStu(@Param("age") Integer age,@Param("name")String name
,@Param("clsId") Long clsId,@Param("id")Long id);
7.bind
-
bind
元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。
-
需求:通过用户name 进行模糊查询
<select id="listLike" resultType="cn.sycoder.domain.Student">
<bind name="ret" value="'%' + name + '%'"/>
select * from student
where name like #{ret}
</select>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)