MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。动态 SQL 可以彻底处理条件地串联 SQL 字符串减少程序员的压力,让程序员将更多地精力投入开发业务中。
MyBatis 中用于实现动态 SQL 的元素主要有:
#{
}占位符,预编译,先编译好sql语句在取值,防止sql注入(传值时使用)
${
}拼接符,会传入参数字符中,取值后再编译sql,不能防止注入
${
}适用于select * from user order by ${
name}
insert into user values (3,'jim',22)
useGeneratedKeys="true"返回主键
keyProperty="id" 用bean下的属性接收
keyColumn="id" 数据库中的列
会进行判断,如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或 OR 开头,它会剔除掉AND 或 OR。
<select id="findUser" resultType="User">
select * from user
<where>
<if test="address!=null">
and address = #{address}
if>
<if test="user_name!=null">
and user_name = #{user_name}
if>
where>
select>
其实用 trim 也可以表示,当 WHERE 后紧随 AND 或则 OR 的时候,就去除 AND 或者 OR。prefix 前缀,prefixOverrides 覆盖首部指定内容
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分
<select id="findUser" resultType="User">
select * from user
<trim prefix="where" prefixOverrides="and | or">
<if test="address!=null">
and address = #{address}
if>
<if test="user_name!=null">
and user_name = #{user_name}
if>
trim>
select>
<select id="findUser1" resultType="User">
select * from user
<where>
<if test="user_name!=null">
and user_name like concat('%',#{user_name},'%')
if>
where>
select>
<update id="update" parameterType="User">
update user
<set>
<if test="userName!=null">
user_name = #{userName},
if>
<if test="age!=null">
age = #{age},
if>
<if test="mobile!=null">
mobile = #{mobile},
if>
<if test="address!=null">
address = #{address}
if>
set>
where id = #{id}
update>
也可以使用trim实现
<update id="update" parameterType="User">
update user
<trim prefix="set" suffixOverrides=",">
<if test="userName!=null">
user_name = #{userName},
if>
<if test="age!=null">
age = #{age},
if>
<if test="mobile!=null">
mobile = #{mobile},
if>
<if test="address!=null">
address = #{address}
if>
trim>
where id = #{id}
update>
主要用在构建 in 条件中,它可以在 SQL 语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。
在使用 foreach 的时候最关键的也是最容易出错的就是 collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的。
– 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
– 如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为array
适用范围,删除多个数据
item 表示集合中每一个元素进行迭代时的别名
index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置
open 表示该语句以什么开始
separator 表示在每次进行迭代之间以什么符号作为分隔符
close 表示以什么结束
<delete id="deleteUser" parameterType="User">
delete from user where id IN
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
foreach>
delete>
在 mybatis 中的 xml 文件中,存在一些特殊的符号,比如:<、>、"、&、<>
等,正常书写 mybatis 会报错,需要对这些符号进行转义。具体转义如下所示:
特殊字符 转义字符
< <
> >
" "
’ '
& &
也可以使用来包裹特殊字符,但是这种方式所在的内容会被解析器忽略,应减少使用
<if test="id != null">
AND #{id} ]]>
if>