赞
踩
这片文章是对自己学习的总结,学习材料来源网上。
<foreach>标签用于在映射器中,定义sql逻辑时,需要遍历集合内元素的场景。
很常见的一个情况是,传入一个List<Integer>集合,里面是userId,要求返回这个id集合的所有用户信息。
那么定义sql语句就如下所示。
- <select id="findUsersByIds" parameterType="list" result="com.luckincoffee.domain.User">
- select * from users where user_id in
- <foreach index="index" open="(" close=")" separator="," collection="list" item="item">
- #{item}
- </foreach>
- </select>
这样就能达到我们的目的。接下来就详细讲解foreach标签各个属性的意义。
select * from users where user_id in (1,2,3)
foreach就是后面的(1,2,3),他其实也就是字符串而已。那么open="("意思就是在1,2,3之前加上'('。
select * from users where user_id in (1 2 3)
- <select id="findUsersByIds" parameterType="list" result="com.luckincoffee.domain.User">
- select * from users where user_id in
- <foreach index="index" open="(" close=")" separator="," collection="list" item="userId">
- #{userId}
- </foreach>
- </select>
如果我们的参数传的是User类,User类中有classIdList这么一个列表,我们需要用foreach对这个列表遍历。这个时候,foreach中的collection标签就是用来指明对classIdList来进行遍历,否则计算机会不知道应该把哪个属性来当做集合遍历。
- <select id="select" parameterType="com.company.domain.User" resultType="com.company.domain.User">
- select * from t_user
- where t_user.class_id in
- <foreach collection="classIdList" open="(" close=")" separator="," item="item">
- #{item}
- </foreach>
- </select>
当然,如果传进来的参数就是一个集合,那collection可以省略。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。