总结一下工作中使用到的动态Sql.
if 和 where 标签
<!--动态Sql : where / if-->
<select id="getItems" resultType="com.hs.bean.Item">
select * from Items
<where>
<if test="id != null and id != 0">
AND id = #{id}
</if>
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="county != null and county != ''">
AND county = #{county}
</if>
</where>
</select>
多个查询条件,通常会使用 标签来进行控制。 标签可以自动的将第一个条件前面的逻辑运算符 (or ,and) 去掉.
choose、when、otherwise 标签
这三个标签需要组合在一起使用,类似于 Java 中的 switch、case、default。只有一个条件生效,也就是只执行满足的条件 when,没有满足的条件就执行 otherwise,表示默认条件。
<!--动态Sql: choose、when、otherwise 标签-->
<select id="getItem2" resultType="com.hs.bean.Item">
select * from Item
<where>
<choose>
<when test="name != null and name != ''">
AND name = #{name}
</when>
<when test="county != null and county != ''">
AND county = #{county}
</when>
<otherwise>
AND id = #{id}
</otherwise>
</choose>
</where>
</select>
在测试类中,即使同时添加name和county的值,最终的sql也只会添加第一个属性值。
3选1
set 标签
使用set标签可以将动态的配置 SET 关键字,并剔除追加到条件末尾的任何不相关的逗号。使用 if+set 标签修改后,在进行表单更新的操作中,哪个字段中有值才去更新,如果某项为 null 则不进行更新,而是保持数据库原值。
<!--动态Sql: set 标签-->
<update id="updateSet" parameterType="com.hs.bean.Item">
update Item
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="county != null and county != ''">
county = #{county},
</if>
</set>
where id = #{id}
</update>
foreach 标签
foreach标签主要有以下参数:
item :循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在list和数组中是其中的对象,在map中是value。
index :在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
open :表示该语句以什么开始
close :表示该语句以什么结束
separator :表示元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
list批量插入
<!--动态Sql: foreach标签, 批量插入-->
<insert id="dynamicSqlInsertList" useGeneratedKeys="true" keyProperty="id">
insert into users (name, age, county, date)
values
<foreach collection="list" item="user" separator="," >
(#{user.name}, #{user.age}, #{user.county}, #{user.date})
</foreach>
</insert>
<!--动态Sql: foreach标签, list参数查询-->
<select id="dynamicSqlSelectList" resultType="com.hs.bean.Item">
SELECT * from Item WHERE id in
<foreach collection="list" item="id" open="(" close=")" separator="," >
#{id}
</foreach>
</select>
map参数
< map> 标签需要结合MyBatis的参数注解 @Param()来使用,需要告诉Mybatis配置文件中的collection="map"里的map是一个参数:
<!--动态Sql: foreach标签, map参数查询-->
<select id="dynamicSqlSelectMap" resultType="com.lks.bean.User">
select * from users WHERE
<foreach collection="map" index="key" item="value" separator="=">
${key} = #{value}
</foreach>
</select>