动态SQL概述
根据实体类的不同取值,使用不同的 SQL 语句来进行查询;在多条件组合查询中经常使用
动态 SQL 标签
根据实体类的不同取值,使用不同的 SQL 语句来进行查询
某个属性符合某个条件时,再进行该属性的条件查询
<select id="findQuery" parameterType="User" resultType="User">
SELECT id, username, birthday, sex, address FROM user
<where>
<if test=" sex!=null and sex != '' ">
AND sex = #{sex}
</if>
<if test="username!=null and username != ''">
AND username like #{username}
</if>
<if test="address!=null and address != ''">
AND address like #{address}
</if>
<if test="birthday!=null and birthday != ''">
AND birthday = #{birthday}
</if>
</where>
</select>
choose、when、otherwise
从多个条件中选择一个使用。MyBatis 提供了 choose 元素,类似于 Java 中的 switch 语句
其中一个when
符合条件则使用该when内的sql查询,都不符合则使用otherwise
内的sql查询
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
where
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。
而且,若子句的开头为 “AND” 或 “OR”,where 元素会将它们去除
<select id="findUserById" resultType="cn.dy.pojo.User" parameterType="java.lang.Integer">
SELECT username,birthday,sex,address FROM user
<where>id = #{id}</where>
</select>
set
动态更新语句的类似解决方案叫做 set
set 元素可以用于动态包含需要更新的列,忽略其它不更新的列
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
trim
自定义 trim 元素来定制 where 元素的功能。
where 元素等价的自定义 trim 元素
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)
上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容
set 元素等价的自定义 trim 元素
<trim prefix="SET" suffixOverrides=",">
...
</trim>
foreach
用于遍历集合(List,Map,Set)等
允许指定开头与结尾的字符串以及集合项迭代之间的分隔符
属性collection
:代表要遍历的集合元素类型open
:forEach遍历之前添加的内容close
:forEach遍历之后添加的内容index
:List时代表索引,Map时,代表键item
:List时代表遍历集合的每个元素,Map时,代表值sperator
:迭代项之间的分隔符
例:
<select id="findByIds" resultType="User" parameterType="java.lang.Integer">
SELECT id, username, birthday, sex, address FROM user
<where>
id IN
<foreach collection="list" open="(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
sql
定义公用代码片段
例:
<!-- 定义代码片段 -->
<sql id="userAll">SELECT id, username, birthday, sex, address FROM user</sql>
<!-- 使用代码片段 -->
<select id="findAll" resultType="cn.dy.pojo.User">
<include refid="userAll"></include>
</select>