1.where顺少、if
<select id="findUserList" parameterType="cn.ztc.mybatis.po.UserQueryVo" resultType="cn.ztc.mybatis.po.UserCustom">
select * from user
<!-- where可以自動(dòng)的去掉條件中的第一個(gè)and -->
<where>
<if test="userCustom.sex!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</where>
</select>```
2.sql片段
<!-- 定義sql片段
一般是基于單表來(lái)定義sql片段坝茎,這樣的sql片段可重用性高
在sqk片段中不要包含where
-->
<sql id="query_user_where">
<if test="userCustom.sex!=null!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</sql>
<select id="findUserList" parameterType="cn.ztc.mybatis.po.UserQueryVo" resultType="cn.ztc.mybatis.po.UserCustom">
select * from user
<!-- 可以自動(dòng)的去掉條件中的第一個(gè)and -->
<where>
<!-- 引用sql片段 -->
<include refid="query_user_where"></include>
</where>
</select>```
3.foreach
<sql id="query_user_where">
<if test="userCustom.sex!=null!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
<if test="ids!=null">
<!-- 使用foreach遍歷ids
collection:指定輸入對(duì)象中的集合屬性名
item:遍歷生成的對(duì)象名
open:開(kāi)始遍歷時(shí)的拼接串
close:結(jié)束遍歷時(shí)的拼接串
separator:遍歷的兩個(gè)對(duì)象中間的拼接串
-->
<foreach collection="ids" item="user_id" open="and(" close=")" separator="or">
<!-- 每次遍歷需要拼接的串
and( id=? or id=? or id=? )
-->
id=#{user_id}
</foreach>
</if>
</if>
</sql>```