Mybatis动态Sql的Foreach遍历拼接输入参数中的List或数组

pojo、pojo包装类

public class User {
	private int id;
	private String username;
	private String sex;
	private Date birthday;
	private String address;
	//省略get/set方法
}


//继承User类
public class UserCustom extends User {

}

/*
包装类
 * */
public class UserQueryVo {
	private UserCustom userCustom;
	private List<Integer> ids;	//从pojo类中读取List
}

当paramterType是UserQueryVo时,需要取出ids的值,用foreach遍历

UserMapper.xml

<sql id="findUser_where">
		<if test="userCustom">
			<if test="userCustom.sex != null and userCustom.sex != ''">
				and sex = #{userCustom.sex}
			</if>
			<!--  
				使用foreach遍历传入的ids集合
				collection:指定输入的对象中集合的属性
				item:每次遍历的元素生成的对象
				open:开始遍历时生成的串
				close:结束遍历时生成的串
				separator:遍历的两个对象中需要生成的串
			 -->
			<if test="ids != null">
                 <!--最终生成的SQL语句: select * from user where sex = '' and (id= or id= or id= ) and username like '' -->
				<foreach collection="ids" item="user_id" open="and (" close=")" separator="or">
				<!-- 每个遍历需要生成的串 -->
					id=#{user_id}
				</foreach>
			</if>
             <!-- 与上面的foreach等价
			<if test="ids != null">
                  最终生成的SQL语句: select * from user where sex = '' and id in(1,2,3) and username like ''
				<foreach collection="ids" item="user_id" open="and id in(" close=")" separator=",">
					#{user_id}
				</foreach>
			</if>
			
			 -->
			<if test="userCustom.username != null and userCustom.username != ''">
				and username like '%${userCustom.username}%'
			</if>
		</if>
	</sql>
    <select id="findUserByIds" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom">
		select * from user
		<!-- 最好不要将where语句包括进去 -->
		<where>
			<!-- 引用sql片段 ,如果refid指定的id不在本mapper中,需要指定namesapce-->
			<include refid="findUser_where"></include>
		</where>
	</select>




  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值