最近在学习MyBatis相关知识,觉得有必要总结一下,因此会有相关几篇文章介绍一下MyBatis知识点,如果文章有错欢迎大家指正!
我们知道MyBatis的强大特性之一便是它的动态 SQL。 使用过JDBC或其他类似框架的人都会知道, 根据不同条件拼接SQL 语句时不仅不能忘了必要的空格, 还要注意省略掉列名列表最后的逗号, 处理方式麻烦且凌乱。 MyBatis的动态SQL 则能让我们摆脱这种痛苦。
MyBatis的动态SQL在XML中支持的几种标签:
- if
- choose(when、otherwise)
- trim(where、set)
- foreach
- bind
一、if用法
1、在WHERE条件中使用if
当我们需要查询某些条件时,使用到if。
比如,下面的查询语句必须要同时传入username和email才能查询出正确结果,如果只传入一个便会导致另一个的结果为null,查不出符合的结果。
<select id="selectByUser" resultType="User">
select id, username, password, expried, disabled, email from user
where username like concat('%', #{userName},'%')
and email = #{email}
</select>
这个时候就需要使用到if了。我们更改如下:
<select id="selectByUser" resultType="User" >
select id, username, password, expried, disabled, email from user
where 1=1
<if test="username != null and username != ' '">
and username like concat('%', #{username},'%')
</if>
<if test="email!= null and email != ' '">
and email = #{email}
</if>
</select>
- 判断条件 property != null 或 property == null:适用于任何类型的宇段,于判断属性值是否为空。
- 判断条件 property != ’ ’ 或 property == ’ ':仅适用于 String 类型的宇段 ,用于判断是否为空字符串。
- and 和 or :当有多个判断条件时,使用and或or进行连接,嵌套的判断可以使用小括号分组,and相当于Java中的与(&&), or 相当于Java中的或(||)。
这里我们使用了where 1=1 ,来使得整体SQL合法,但是不太美观,后面可以通过where标签来替换。
2、在UPDATE更新列中使用if
在update标签中,我们可以选择有值的字段进行更新,避免字段更新为null。如下:
<update id="update" parameterType="User">
UPDATE user
<set>
<if test="username != null and username != ' '">
username = #{username},
</if>
<if test="email!= null and email != ' '">
email = #{email},
</if>
id = #{id}
</set>
WHERE id = #{id}
</update>
在set标签最后加上“id = #{id}”防止当没有值时会SQL语法不对报错的情况发生。
4、在INSERT动态插入列中使用if
比如有些值为空就使用数据库给定默认值,不使用空值。我们就可以判断如果有值就插入,没值就不插入数据库,使用数据库默认值。
如下,需要注意一点就是插入的列和值要对应。
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into user(
username, password,
<if test="email != null">
<if test="email != ''">
email,
</if>
</if>
expried, disabled)
values(
#{username}, #{password},
<if test="email != null">
<if test="email != ''">
#{email},
</if>
</if>
#{expried}, #{disabled})
</insert>
二、choose用法
if标签提供了基本的条件判断, 但是它无法实现if. . . else 、 if … else…的逻辑,要想实现这样的逻辑,就需要用到 choose when otherwise 标签。
choose元素中包含when和otherwise两个标签, 一个choose中至少有一个when, 有0个或者1个otherwise。
比如,根据ID或用户名查找用户,当满足条件时找出需要的条件,否则返回0条数据。如下:
<select id="selectByIdOrUserName" resultType="User">
select id, username, password, expried, disabled, email from user
where 1=1
<choose>
<when test="id != null">
and id = #{id}
</when>
<when test="username != null and username != ''">
and username = #{username}
</when>
<otherwise>
limit 0
</otherwise>
</choose>
</select>
三、where、set、trim用法
这3个标签解决了类似的问题,并且where和set都属于trim的一种具体用法。
1、where
我们使用上面包含if的标签继续,当时使用了where 1=1,在这里可以更改如下:
<select id="selectByUser" resultType="User">
select id, username, password, expried, disabled, email from user
<where>
<if test="username != null and username != ' '">
and username like concat('%', #{username},'%')
</if>
<if test="email!= null and email != ' '">
and email = #{email}
</if>
</where>
</select>
当if条件都不满足的时候,where元素中没有内容,所以在SQL中不会出现where。如果if条件满足,where 元素的内容就是以and开头的条件,where会自动去掉开头的and,这也能保证where条件正确。 这样就去掉了where 1=1的多余SQL。
2、set
set标签的作用:如果该标签包含的元素中有返回值,就插入一个set;如果set后面的字符串是以逗号结尾的,就将这个逗号剔除。
set的用法常在update字段使用,比较简单,这里不再复述。
3、trim
trim标签的作用:where和set标签的功能都可以用trim标签来实现,并且在底层就是通过TrimSqlNode实现的。
比如使用trim实现where标签用法,如下:
<trim prefix="WHERE" prefixOverrides="AND ||OR ">
...
</trim>
注意:这里的AND和OR后面的空格不能省略, 为了避免匹配到andes、 orders等单词 。 实际的prefixeOverrides 包含“AND”、“OR”、“AND\n”、“OR\n”、“AND\r”、OR\r”、 “AND\t”、 “OR\t”, 不仅仅是上面提到的两个带空格的前缀。
set标签对应的 trim 实现如下:
<trim prefix="SET" prefixOverrides=",">
...
</trim>
trim标签的属性如下:
- prefix:当trim元素内包含内容时,会给内容增加prefix指定的前缀。
- prefixOverrides:当trim元素内包含内容时, 会把内容中匹配的前缀字符串去掉。
- suffix:当trim元素内包含内容时,会给内容增加suffix指定的后缀。
- suffixOverrides:当trim元素内包含内容时,会把内容中匹配的后缀字符串去掉。
四、foreach用法
SQL语句中有时会使用IN关键字,例如 id in ( 1 , 2 , 3 )。 可以使用#{ids}方式直接获取值, 但这种写法不能防止SQL注入, 想避免SQL注入就需要用#{}的方式, 这时就要配合使用foreach标签来满足需求。
比如下面的遍历查询:
<select id="selectByIdList" resultType="User">
select id, username, password, expried, disabled, email from user
from user
where id in
<foreach collection="list" open="(" close=")" separator="," item="id" index="i">
#{id}
</foreach>
</select>
foreach 包含以下属性。
- collection : 必填, 值为要选代循环的属性名。 这个属性值的情况有很多。
- item:变量名, 值为从法代对象中取出的每一个值。
- index :索引的属性名, 在集合数组情况下值 为当前索引值 , 当选代循环的对象是Map类型时, 这个值为 Map的key(键值)。
- open:整个循环内容开头的字符串 。
- close : 整个循环内容结尾的字符串。
- separator :每次循环的分隔符 。
collection的填写具有多种类型,如下几种情况:
1、只有一个数组参数或 集合参数
当参数类型为集合的时候, 默认会转换为 Map 类型, 井添加一个key为collection的值( MyBatis 3.3 .0 版本中增加), 如果参数类型是List 集合, 那么就继续添加一个key为 list的值( MyBatis3.2.8 及低版本中只有这一 个 key ),这样, 当 collection=" list ”时,就能得到这个集合, 并对它进行循环操作。
当参数类型为数组的时候 , 也会转换成Map类型,默认的key为 array 。使用数组参数时 , 就需要把foreach 标签中的collection属性值设置为array。
2、有多个参数
当有多个参数的时候, 要使用@Param注解给每个参数指定一个名字, 否则在SQL中使用参数时就会不方便, 因此将collection设置为@Param注解指定的名字即可。
3、参数是 Map 类型
使用Map和使用@Param注解方式类似, 将collection指定为对应Map中的ke 即可 。 如果要循环所传 入的Map , 推荐使用@Param注解指定名字, 此时可将collection设置为指定的名字, 如果不想指定名字 , 就使用默认值_ parameter 。
4、参数是一个对象
这种情况下指定为对象的属性名即可。 当使用对象内多层嵌套的对象时 , 合和数组可以使用下标取值)的 方式可以指定深 层的属性值。
foreach可以做批量操作,比如通过foreach实现批量插入,动态UPDATE。
这里我们介绍一下动态 UPDATE,如下:
<update id="updateByMap">
update user
set
<foreach collection="_parameter" item="val" index="key" separator=",">
${key} = #{val}
</foreach>
where id = #{id}
</update>
在Dao层下,添加接口如下:
int updateByMap(Map<String ,Object> map);
这里没有通过@Param注解指定参数名, 因而MyBatis在内部的上 文中使用了 认值_parameter 作为该参数的 key, 所以在 XML中也使用了_parameter。
五、bind用法
bind标签可以使用OGNL表达式创建一个变量井将其绑定到上下文中。
比如前面在selectByUser这个方法中,使用了like查询条件,代码如下:
<if test="username != null and username != ' '">
and username like concat('%', #{username},'%')
</if>
我们知道在不同数据库拼接字符串的用法不同,所以我们可以使用bind标签来避免更换数据库带来的麻烦。
<if test="username != null and username != ' '">
<bind name="usernameLike" value="'%' + username + '%'"/>
and username like #{usernameLike}
</if>
同时使用bind我们还可以使用其他方法,比如调试bug,后面结合OGNL讲解。
bind标签的两个属性都是必选项,name为绑定到上下文的变量名,value为OGNL 表达式。创建一个bind标签的变量后,就可以在下面直 接使用,使用bind 拼接字符串不仅可以避免因更换数据库而修改SQL,也能预防SQL注入。
六、多数据库支持
在各个标签select、insert、delete、update、selectKey、sql中都包含一个databaseId属性,通过它我们可以来配置使用不同数据库。如下:
<select id="selectByUser" resultType="User" databaseId="mysql">
select id, username, password, expried, disabled, email from user
where 1=1
<if test="username != null and username != ' '">
and username like concat('%', #{username},'%')
</if>
<if test="email!= null and email != ' '">
and email = #{email}
</if>
</select>
这里通过databaseId标签指定select语句是适用MySQL的,就是使用MySQL数据库的。
可以使用 if 标签配合默认的上下文中的 _databaseid 参数这种写法去实现 。 这样可以避免大量重复的SQL 出现, 方便修改。
<select id="selectByUser" resultType="User" >
select id, username, password, expried, disabled, email from user
where 1=1
<if test="username != null and username != ' '">
<if test =” _databaseid == ’ mysql ’”>
and username like concat('%', #{username},'%')
</if>
<if test =” _databaseid == ’oracle ’”>
and username like '%' || #{username} || '%'
</if>
</if>
<if test="email!= null and email != ' '">
and email = #{email}
</if>
</select>
常见的数据库版本配置如下:
<databaseIdProvider type =” DB VENDOR ” >
<property name =” SQL Server ” value =” sqlserver ” />
<property name =” DB2 ” value =” db2 ” />
<property name =” Oracle ” value =” oracle ” />
<property name =” MySQL ” value =”mysql ”/>
<property name =” PostgreSQL ” value =” postgresql ”/>
<property name =” Derby ” value =” derby" />
<property name =” HSQL ” value =” hsqldb ” />
<property name =” H2 ” value =” h2 ” />
</databaseIdProvider>
七、OGNL用法
在MyBatis的动态SQL和${}形式的参数中都用到了OGNL表达式,MyBatis常用的OGNL表达式如下:
- e1 or e2
- e1 and e2
- e1 == e2 或 e1 eq e2
- e1 != e2 或 e1 new e2
- e1 lt e2: 小于
- e1 lte e2:小于等于,其他表示为gt(大于)、gte(大于等于)
- e1 + e2、e1 * e2、e1/e2、e1 - e2、e1 % e2
- !e 或not e:非,取反
- e.method(args):调用对象方法
- e.property:对象属性值
- e1[ e2 ]:按索引取值(List、数组和Map)
- @class@method(args):调用类的静态方法
- @class@field:调用类的静态字段
一般使用OGNL表达式,如下:
<if test ="list != null and list.size() > 0" >
<!其他>
</if>
表达式 1 2 通常用于简化一些校验, 或者进行更特殊的校 验,例如 if 中常见的判断可以写成如下这样。
<if test ="@net.anumbrella.mybatis.util.StringUtil@isNotEmpty(username)" >
and username like concat('%', #{username},'%')
</if>
StringUtil工具类如下:
public class StringUtil {
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
}
我们可以通过bind标签来进行一些参数的调试工作,如下:
<bind name="print" value="@net.anumbrella.mybatis.util.StringUtil@print(_parameter)"/>
添加打印方法,
public static void print(Object value){
System.out.println(value);
}
如此一来我们便可以对SQL参数进行调试。
最后,写了一个MyBatis结合Spring Boot的demo代码,可以参考理解一下。