mybatis的xml文件中使用for循环遍历
一般遍历会有两种,一个是单个属性,另外一个是多个属性
单个属性的:
<select id="selectList" parameterType="java.lang.String" resultType="com.dd.model.User">
select * from user a where a.del_flag = 0
<if test="userAccountList != null and userAccountList .size() > 0">
and a.account in
<foreach item = "account" collection="userAccountList" open="(" separator="," close=")">
#{account}
</foreach>
</if>
这边如果a.del_flag没有要求的话,可以用<where>标签。
多个属性的:
<select id="selectList" parameterType="com.dd.model.User" resultType="com.dd.model.User>
select * from user a
<where>
<foreach collection="userAccountList" item="item" index="i" open="(" separator=" " close=")">
<if test="!=0">or</if>
( a.account=#{item.account} and a.name={item.userName} )
</foreach>
</where>
</select>
核心就是那个<if>里面的判断,这样写的话第一个就不加or,后面就会拼上or;
这里代码层要先处理userAccountList不能为空,如果为空直接返回,不执行该SQL;
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步