mybatis动态sql使用的标签:java
1:if 判断sql
2:where 解决sql语句拼接条件问题数组
例:
mybatis
<select id="findUserById" resultType="user">dom
select * from user where spa
<where>
code
<if test="id != null">orm
id=#{id}it
</if>io
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 ]]>