使用说明:
序号 | 用法 | 相当于 | 说明 |
---|---|---|---|
1 | gt | > | 大于 |
2 | gte | >= | 大于等于 |
3 | lt | < | 小于 |
4 | lte | <= | 小于等于 |
5 | eq | == | 相等 |
6 | neq | != | 不相等 |
7 | and | && | 并且 |
8 | or | || | 或者 |
9 | list.isEmpty() | 是否为空 | 是否为空,用于list判断是否为空。 |
10 | list.size() | 长度 | 获取list的长度 |
11 | str.indexOf(' ') | 检索 | 检索 |
12 | str.lastIndexOf(' ') | 从尾部检索 | 从尾部检索 |
13 | str.toString() | 转字符串 | 转字符串 |
另外提示:由于mybatis使用xml结构,xml中的尖括号“<>” 是特殊的,所以xml中的sql大小于符号需做特殊处理
> 可使用 >
< 可使用 <
>= 可使用 >=
<= 可使用 <=
例如:查询t_user表中年龄大于等于18岁的:select * from t_user where age >= 18;
使用案例:
1.判断String是否为空
<if test="stringParam != null and stringParam != ''"></if>
2.判断Integer是否大于0
<if test="idParam !=null and idParam gt 0"></if>
3.判断List是否不为空
<if test="listParam !=null and listParam.size >0"></if>
4.判断String是否以某特定字符(比如此处的"user")开头
<if test="stringParam.indexOf('user') != -1"></if>
<!-- 是否以什么开头 -->
<if test="stringParam!= null and stringParam.indexOf('user') == 0"> </if>
<!-- 是否包含某字符 -->
<if test="stringParam!= null and stringParam.indexOf('user') >= 0"> </if>
<!-- 是否以什么结尾 -->
<if test="stringParam!= null and stringParam.lastIndexOf('user') > 0"></if>
5.判断字符串是否等于特定字符(比如此处的user)
<if test='stringParam != null and stringParam == "user"'></if>
<!-- 注意不能使用此写法,即最外边用双引号,里边用单引号,此写法会抱java.lang.NumberFormatException异常 -->
<if test="stringParam != null and stringParam != 'user'"></if>
<!-- 如果要用这个写法要 -->
<if test="stringParam != null and stringParam != 'user'.toString()"></if>
6.是否是某个特定字符串,某些业务有此需要。
<if test="username != null and 'hello' == username"></if>
或者
<if test="username != null and 'hello' eq username"></if>
7.foreach集合的遍历,通常是构建in条件语句的时候使用
- collection:指定遍历的集合名:Mybatis会将传入的list封装到map中,map中的键就是list,也可以用注解@param("")决定所封装的别名
- item:将当前遍历的对象取一个名方便调用,调用方法#{对象名}
- index:若遍历的对象是list时,index就表示list的索引,item表示当前的值,若遍历的对象是一个map的时候,index表示map的key,item表示map的value
- open:遍历的开始符
- close:遍历的结束符
- separator:表示遍历元素之间的分隔符
<select id="ListStudentByConditionForeach" resultType="com.cn.cmc.bean.Student">
select * from student
<foreach collection="list" item="item_id" open="where id in(" close=")" separator=",">
#{item_id}
</foreach>
</select>
8.返回主键id
<insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="com.cn.cmc.bean.Student">
9.批量插入
<insert id="addAllStudent" parameterType="com.cn.cmc.bean.Student">
insert into student(name, sex, age) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.name}, #{item.sex}, #{item.age})
</foreach>
</insert>
官方文档:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html
如有遗漏,欢迎留言补充,谢谢