Mybatis动态Sql
MyBatis 中用于实现动态 SQL 的元素主要有:
If ,where,trim,set,choose (when, otherwise),foreach
If 元素:
if 标签可以对传入的条件进行判断
<select id="findUserList" parameterType="User" resultType="User">
select
id,name,birthday
from user where 1=1
<if test="name!=null">
and name=#{name}
</if>
<if test="id!=null">
and id=#{id}
</if>
</select>
上述代码中如果没有1=1 判断语句,将会很麻烦.
where元素:
当查询条件个数不确定时,可以运用where语句来解决上述出现的问题.
<select id="findUserList" parameterType="User" resultType="User">
select
id,name,birthday
from user
<where>
<if test="name!=null">
name=#{name}
</if>
<if test="id!=null">
and id=#{id}
</if>
</where>
</select>
元素将会进行判断,如果标签有返回值,那么将会插入一个where ,此外,如果标签中返回内容以OR || AND开头,那么他会自动删除.不会造成代码紊乱.
trim元素:
where标签,其实也可以用trim来表示,当where后缀有and和or 时,他将会删除.prefix前缀,,prefixOverrides覆盖首部指定内容.
<select id="findUserList" parameterType="User" resultType="User">
select
id,name,birthday
from user
<trim prefix="where" prefixOverrides="and">
<if test="name!=null">
name=#{name}
</if>
<if test="id!=null">
id=#{id}
</if>
</trim>
</select>
set元素:
他可以把最后一个元素后的逗号去掉.
<update id="updateUser" >
update user
<set >
<if test="name!=null">
name=#{name},
</if>
<if test="id!=null">
birthday=#{birthday},
</if>
</set>
<where>
id=#{id}
</where>
</update>
foreach元素:
主要是在in 条件下完成,他可以在sql语句中完成一个集合的迭代.
foreach元素的属性主要有 item,index,collection,open,separator,close。
item:表示集合中每一个元素进行迭代时的别名
index:指定一个名字,用于表示在迭代过程中,每次迭代到的位置
open:表示该语句以什么开始
separator:r 表示在每次进行迭代之间以什么符号作为分隔符
close:表示以什么结束
collection:
- 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
- 如果传入的是单参数且参数类型是一个 Array数组的时候,collection 属性值为 array
<delete id="deleteUser">
delete from user where id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>