MyBatis动态SQL
MyBatis提供对SQL语句进行动态组装的能力,使用XML的简单元素便能完成动态SQL的功能。
元素介绍
元素名称 | 元素描述 |
---|---|
if | 判断语句,属于当条件分支判断 |
choose-when-otherwise | 类似于switch语法,是多条件分支判断 |
foreach | 循环语句,常用于in语句的列举条件中 |
test | 用于判断真假,常用于判断中 |
where | 相当于SQL中的where,但是可以加入条件判断是否和SQL语句组装 |
trim | 用于去掉SQL中的一些特殊字符串 |
set | 用于update中,与if何用达到可以对信息摘取更新的作用 |
元素使用的例子
数据表设计为:t_user(id,name,comment)
- if元素
要求:
根据名字name查找指定用户数据,其中name是一个选填条件,当没有填写时不作为查询条件。
<select id="findUser" parameterType="string" resultMap="userMap">
select id,name,comment
from t_user
where 1 = 1
<!-- 此处的 1=1 仅仅是当条件不满足时保证SQL语句不报错的作用 -->
<if test="name != null and name != ' '">
and name like concat('%',#{name },'%')
</if>
</select>
- choose-when-otherwise元素
要求:
根据id,name,comment三个属性查找
如果id不为空,只用id查找
如果id为空name不为空,只用name查找
如果id,name为空则要求comment不为空
<select id="findUser" parameterType="user" resultMap="userMap">
select id,name,comment
from t_user
where 1=1
<!-- 此处的 1=1 仅仅是当条件不满足时保证SQL语句不报错的作用 -->
<choose>
<when test="id != null and id !=' '">
and id = #{id}
</when>
<when test="name != null and name !=' '">
and name like concat('%',#{name},'%')
</when>
<otherwise>
and note is not null
</otherwise>
</choose>
</select>
- where元素
这个元素只是替代了where语句而已,只有当where元素里面的条件成立时,才将where关键字组装到SQL语句里面去。
要求:
根据name和comment进行模糊查询
<select id="findUser" parameterType="user" resultMap="userMap">
select id,name,comment
from t_user
<where>
<if test="name != null and name != ' '">
and name like concat('%',#{name },'%')
</if>
<if test="comment != null and comment != ' '">
and comment like concat('%',#{comment },'%')
</if>
</where>
</select>
- trim元素
去除掉特殊的SQL语法就可以使用这个元素,比如去除and,or等等。
prefix : 表示语句的前缀
prefixOverrides : 表示需要去掉的字符串
<select id="findUser" parameterType="string" resultMap="userMap">
select id,name,comment
from t_user
<trim prefix="where" prefixOverrides="and">
<if test="name != null and name != ' '">
and name like concat('%',#{name },'%')
</if>
</select>
- set元素
要求:
根据id对指定用户的部分信息或全部信息进行更新
<update id="updateUser" parameterType="user">
update t_user
<set>
<if test="name != null and name != ' '">
name = #{name},
</if>
<if test="comment != null and comment != ' '">
comment = #{comment}
</if>
</set>
where id = #{id }
</update>
- foreach元素
foreach支持数组,List,Set接口的集合并提供遍历。
要求:
对一个List<Integer>的用户id集合idList通过foreach元素找到这个集合中每个id对应的用户信息
collection : idList是传递进来的参数名
item :循环中当前元素
index :当前元素在集合中的下标
open/close :用什么符号将集合元素包装起来
separator :各个元素的间隔符
<select id="findUserBySex" resultMap="user">
select *
from t_user
where id in
<foreach item="id" index="index" collection="idList"
open="(" separator="," close=")">
#{id}
</foreach>
</select>