javamagicsun 2019-10-28
MyBatis 的强大特性之一便是它的动态 SQL。 闲话少说,代码撸起来!

IF 这基本上是where的必需品了
public interface BlogMapper {
//这个地方需要注解 @Param 对这个参数进行命名,要不然if的时候获取不到参数名称
List<Blog> selectByTitle(@Param("title") String title);
}<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 绑定Dao接口,之后,你可以不用写接口实现类,
mybatis会通过与id同名的接口自动帮你找到对应要执行的SQL语句 -->
<mapper namespace="cm.mbs.dao.BlogMapper">
<!--模糊查询的时候三种写法任选其一就可以了-->
<select id="selectByTitle" resultType="Blog">
select * from blog where 1=1
<if test="title != null and title.trim() != ‘‘">
and title like concat(‘%‘,#{title},‘%‘)
</if>
<!--<if test="title != null and title.trim() != ‘‘">
and title like ‘%${title}%‘
</if>-->
<!--<if test="title != null and title.trim() != ‘‘">
and title like "%"#{title}"%"
</if>-->
</select>
</mapper>有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
List<Blog> selectByExample(Blog blog);
<select id="selectByExample" resultType="Blog">
select * from blog where 1=1
<choose>
<when test="title != null and title.trim() != ‘‘">
and title like concat(‘%‘,#{title},‘%‘)
</when>
<when test="state != null and state.trim() != ‘‘">
and state like concat(‘%‘,#{state},"%")
</when>
<otherwise>
and featured = 1
</otherwise>
</choose>
</select>where这个标签会自动的为你去出第一个条件前面的and|or 这样就不会出错了。例如:
<select id="selectWhere" resultType="Blog">
select * from blog
<where>
<if test="title != null and title.trim() != ‘‘">
and title like concat(‘%‘,#{title},‘%‘)
</if>
<if test="state != null and state.trim() != ‘‘">
and state like concat(‘%‘,#{state},"%")
</if>
</where>
</select>where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
如果 where 元素没有按正常套路出牌,我们可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
set标签会自动的为我们忽略掉最后一个逗号例如:
Integer updateBlog(Blog blog);
<update id="updateBlog" parameterType="Blog" >
update blog
<set>
<if test="title != null">title = #{title},</if>
<if test="state != null">state = #{state},</if>
</set>
where id = #{id}
</update>这里会只能的为你忽略掉最后的一个逗号防止出错
动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:
List<Blog> selectInAuthorId(String[] arr);
<select id="selectInAuthorId" resultType="Blog">
select * from blog where authorId in
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>注意 collection这个属性最容易出错了,一般这个属性表示的是你传过来的容器是什么,如果是数组,那么你就可以写成 array 是list 就可以写成 list 是 map 就可以写成 map 有的时候你会看到同行写的代码是直接引用注解中的参数名字 ,这样mybatis会忽略类型,按名字引入。这个时候要使用@param:
public User queryUserByParams(@Param("id") Integer id, @Param("userName") String userName);