MyBatis 的强大特性之一即是它的动态 SQL。 闲话少说,代码撸起来!数组
IF 这基本上是where的必需品了mybatis
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 语句。app
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 这样就不会出错了。例如:ide
<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 元素也会将它们去除。spa
若是 where 元素没有按正常套路出牌,咱们能够经过自定义 trim 元素来定制 where 元素的功能。好比,和 where 元素等价的自定义 trim 元素为:code
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
set标签会自动的为咱们忽略掉最后一个逗号例如:xml
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>
这里会只能的为你忽略掉最后的一个逗号防止出错blog
动态 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:it
public User queryUserByParams(@Param("id") Integer id, @Param("userName") String userName);