MyBatis常用语法
总结一下常用的一些mybatis的语法
模糊查询
模糊查询可以使用concat函数和"%"#{parm}"%"两种方式,推荐使用concat方式
,因为在使用druid连接池的时候第二种方式会报错。示例如下
<!-- concat -->
<select id="findList" resultType="com.demo.vo.SysUserListVo">
SELECT
<include refid="Base_Column_List"/>
FROM
sys_user
WHERE
invalid = 0
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
ORDER BY
id DESC
</select>
<!--"%"#{parm}"%"-->
<select id="findList" resultType="com.demo.vo.SysUserListVo">
SELECT
<include refid="Base_Column_List"/>
FROM
sys_user
WHERE
invalid = 0
<if test="name!=null">
and name like "%"#{name}"%"
</if>
ORDER BY
id DESC
</select>
条件判断
多个条件的与非逻辑判断
连接符不能使用&&,但可使用|| or and 三种
数字
非空判断
<if test='id != null'>
and id=#{id}
</if>
比较运算符判断
描述 | 符号 | 运算符 |
---|---|---|
大于 | gt | > |
大于等于 | gte | >= |
小于 | lt | <(不能使用,会报错) |
小于等于 | lte | <=(不能使用,会报错) |
等于 | == | |
不等于 | != |
<if test='age!= null and age> 28'></if>
<if test='age!= null and age gt 28'></if>
···
字符串
- 一般的非空与非空字符串判断
<if test="orgUid != null and orgUid != ''"></if>
- 判断字符串是否已某个特俗字符开头,结尾等
<if test="name != null and name.indexOf('z') == 0"> </if> <!-- 是否以什么开头 -->
<if test="name != null and name.indexOf('z') >= 0"> </if> <!-- 是否包含某字符 -->
<if test="name != null and name.lastIndexOf('z') == name.length()-1"></if> <!-- 是否以什么结尾 -->
判断list是否为空
可以调用size()>0或isEmpty()
<if test="userList != null and userList.isEmpty()"></if>
<if test="userList != null and userList.size()>0"></if>
布尔值判断
布尔值只有 0 和 1 两种值
<if test="flag == 0"></if>
<if test="flag == 1"></if>
数组遍历
<if test="ids != null and ids.length != 0">
and id in
<foreach collection="ids" item="id" separator="," open="(" close=")" index="index">
<if test="index != 1">
#{id}
</if>
</foreach>
</if>
choose when otherwise 相当于 if else 语句
<choose>
<when test="parentId!=null and parentId!=''">
and parent_id=#{parentId}
</when>
<otherwise>
and parent_id=0
</otherwise>
</choose>