1、if判断
<select id="getCategory" parameterType="EshopShopCategory" resultMap="EshopCategory" >
SELECT * from CATEGORY t WHERE (1=1)
<if test="shopCategoryId!=null">
AND t.category_id =#{shopCategoryId}
</if>
<if test="shopCategoryName!=null">
AND t.CATEGORY_NAME like '%${shopCategoryName}%'
</if>
<if test="shopId==null">
AND t.shop_id=0
</if>
ORDER BY SEQUENCE_NO
</select>
2、where,set用来避免当if动态条件都不成立时,或者第一个条件不成立第二个条件成立时出现病态sql
where标签可以自动去除是“AND”或“OR”开头的sql中的“AND”或“OR”关键字
set标签代替了sql中set关键字,set标签可以自动去除sql中的多余的“,”
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
其自定义如下:
<select id="queryBy" resultType="com.scme.pojo.User" parameterType="com.scme.pojo.User">
select * from user
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="username!=null and password!=null">
and username=#{username} and password=#{password}
</if>
</trim>
</select>
<update id="updateUser" parameterType="com.scme.pojo.User">
update user
<trim prefix="set" prefixOverrides=",">
<if test="username!=null"> username=#{username} </if>
</trim>
</update>
3、choose
<select id="getHome" resultType="com.ouyin.domain.Goods">
SELECT
gd.*,sp.sid
FROM
tb_goods gd,tb_shop sp
WHERE
gd.sid=sp.sid
<choose>
<when test="type==1">ORDER BY gd.dateline DESC</when>
<when test="type==2">ORDER BY gd.low_price ASC</when>
<when test="type==3">ORDER BY gd.low_price DESC</when>
<otherwise>ORDER BY gd.sold DESC</otherwise>
</choose>
LIMIT #{start},3
</select>
4、foreach
<select id="selectNumInOrder" resultType="String">
select count(0) from order a left join item b on a.ORDER_ID = b.ORDER_ID
where a.STATUS in ('1','2','3','5')
<if test="list.size() > 0">
and b.PHONE_NUM in
<foreach item="numberList" collection="list" open="(" separator="," close=")">
#{numberList.num}
</foreach>
</if>
</select>
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
其中,当使用可迭代对象或者数组时,index是当前迭代的次数,item的值是本次迭代获取的元素。当使用字典(或者Map.Entry对象的集合)时,index是键,item是值。collection标签可以填('list','array','map')。