标签:
mybatis动态sql使用的标签:
1:if 判断
2:where 解决sql语句拼接条件问题
例:
<select id="findUserById" resultType="user">
select * from user where
<where>
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</where>
</select>
如果id = null 则sql语句会为: select * from user where and and deleteFlag=0,很明显这个是错误的sql语句。添加where便签变可以解决,如上<where></where> 去掉上面红色部分where
3:trim 处理拼接
2中的问题也可以这样处理
<select id="findUserById" resultType="user">
<trim prefix="where" prefixOverrodes="and | or">
select * from user where
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</trim>
</select>
4: set
<update id="updateUser" parameterType="com.domin.User">
update user set
<set>
<if test="name != null">
name = #{name},
</if>
</set>
and deleteFlag = 0;
</where>
</update>
如果name = null,则sql语句为update user set and deleteFlag = 0,明显错误。使用<set></set> 替代<set>
也可以是trim处理
5:foreach 循环遍历集合或数组
<select id="selectUser" resultType="domain.domin.User">
select *
from user
where id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
对应的sql如下:
select * from user where id in(item1,item2...)
item1,item2...代表#{item}每次的值
6:choose 相当于java中的swich
格式如下:
<choose>
<when>
语句
</when>
<otherwise>
语句
</otherwise>
</choose>
遇到的问题:
<![CDATA[ AND shelve_at <= #{currentTimeMillis,jdbcType=BIGINT} AND #{currentTimeMillis,jdbcType=BIGINT} < unshelve_at ]]> //不能写成 <![CDATA[ AND shelve_at <= #{currentTimeMillis,jdbcType=BIGINT} < unshelve_at ]]>
标签:
原文地址:http://my.oschina.net/u/2361475/blog/528487