动态SQL 与sql片段 foreach

目的是为了减少代码量   方便

<!-- 动态sql -->
<select id="findUserLists" parameterType="entity.UserQueryVo" resultType="entity.UserCoustom">
select * from userss

<where>
<if test="userCoustom!=null">
<if test="userCoustom.sex!=null and userCoustom.sex!=''">
And sex=#{userCoustom.sex}
</if>
<if test="userCoustom.username!=null and userCoustom.username!=''">
And username=#{userCoustom.username}
</if>

</if>
</where>
</select>

<select id="findUserListLike" parameterType="entity.UserQueryVo" resultType="entity.UserCoustom">
select * from userss

<where>
<include refid="query_user_where"></include>
</where>
</select>

<!-- sql片段 作用是将sql语句中大量使用的部分截取出来 减少代码量
类似于JAVA中的方法封装
-->
<sql id="query_user_where">
<if test="userCoustom!=null">
<if test="userCoustom.sex!=null and userCoustom.sex!=''">
And sex=#{userCoustom.sex}
</if>
<if test="userCoustom.username!=null and userCoustom.username!=''">
And username like '%${userCoustom.username}%'
</if>

</if>
</sql>

<!-- foreach 当选取多个数据的时候使用 比如批量删除等 -->

<select id="findUserForeach" parameterType="entity.UserQueryVo"
resultType="entity.UserCoustom">
Select * From userss Where 1=1
<if test="ids!=null">

<!--
collection 对象中集合的属性名
item 每个遍历生成的对象
open开始遍历时拼接的字符串
close结束遍历时拼接的字符串
separator 连接时使用 例如or或者,
-->


<foreach collection="ids" item="user_id" open="and (" close=")" separator="or">

如果sql语句是select * from userss where id in(id1,id2,id3);  则将上面的属性修改一下

<foreach collection="ids" item="user_id" open="and id in (" close=")" separator=",">

id=#{user_id}
</foreach>
</if>
</select>

原文地址:https://www.cnblogs.com/cpx123/p/7652568.html