mybatis动态sql (二)

1、<if> (单个条件)

 

2、<choose> <when> (多个分支条件)

 

3、<where>用于智能的处理where条件,可以智能地加上和去掉条件中的and

<select>

select * from user

<where>

<if test="userName != null">

and userName like  #{userName}

</if>

<if test="id!= null">

and id= #{id}

</if>

</where>

</select>

 

4、<set>处理update操作,可以智能地去掉或加上set里面的逗号

<update>

update user

<set>

<if test="userName != null"> userName=#{userName},</if>

<if test="password!= null"> password=#{password},</if>

</set>

</update>

 

5、<trim>可以自动为sql添加前缀和后缀,消减前缀字符或后缀字符

<update>

update user

<trim prefix="set" suffixOverride="," suffix="where id=#{id}">

<if test="userName!=null and userName!='' ">

userName=#{userName},

</if>

<if test="password!=null and password!='' ">

password=#{password},

</if>

</trim>

</update>

 

6、foreach循环标记,主要用于循环查询条件,循环更新

循环查询条件:

<select>

select * from user

<where>

id in 

<foreach item="item" index="index" collection="list" open="(" separator="," close=")">

#{item}

</foreach>

</where>

</select>

批量赋值:

<insert>

insert into user(username,password)

values

<foreach item="item" index="index" collection="list" open="" close="" separator=",">

(#{item.userName},#{item.password})

<foreach>

</insert>

解释:

item循环到的某个元素

index循环的索引

collection循环的集合

open循环的开始符号

close循环的结束符号

posted on 2017-02-17 21:16  _故乡的原风景  阅读(207)  评论(0编辑  收藏  举报