通过mybatis提供的各种标签方法实现动态拼接sql。
一、if 和 where
1 <select id="findUserList" parameterType="user" resultType="user"> 2 select * from user 3 <where> 4 <if test="id!=null and id!=''"> 5 and id=#{id} 6 </if> 7 <if test="username!=null and username!=''"> 8 and username like '%${username}%' 9 </if> 10 </where> 11 </select>
where能够自动去掉第一个and
二、foreach
向sql传递数组或List,mybatis使用foreach解析,如下:
需求
传入多个id查询用户信息,用下边两个sql实现:
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE '%张%' id IN (10,89,16)
1 <if test="ids!=null and ids.size>0"> 2 <foreach collection="ids" open=" and id in(" close=")" item="id" separator="," > 3 #{id} 4 </foreach> 5 </if>
三、SQL片段
Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的,如下:
<!-- 传递pojo综合查询用户信息 --> <select id="findUserList" parameterType="user" resultType="user"> select * from user <where> <if test="id!=null and id!=''"> and id=#{id} </if> <if test="username!=null and username!=''"> and username like '%${username}%' </if> </where> </select> <sql id="query_user_where"> <if test="id!=null and id!=''"> and id=#{id} </if> <if test="username!=null and username!=''"> and username like '%${username}%' </if> </sql> <!--使用include引用--> <select id="findUserList" parameterType="user" resultType="user"> select * from user <where> <include refid="query_user_where"/> </where> </select>
tips:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,<include refid="namespace.sql片段”/>