查询前三条记录:
使用sql:
select * from blog where (id = 1 or id = 2 or id = 3);
使用mybatis提供的foreach遍历来写:
item:字段id
connection:集合
open:开始
close:结束
separator:分隔符号
[index]:开始下标
SELECT * FROM blog b WHERE id in <foreach item="id" index="index" collection="ids" open="(" separator="or" close=")"> id = #{id} </foreach>
代码实现:
dao层接口(定义方法)
/** * 遍历查询博客信息 */ List<Blog> conditionQueryForeach(Map map);
dao层接口实现类(Mapper.xml)
<select id="conditionQueryForeach" parameterType="map" resultType="blog"> select * from blog <where> <foreach collection="ids" item="id" separator="or"> id = #{id} </foreach> </where> </select>
测试类
@Test public void conditionQueryForeachTest(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map map = new HashMap();
List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); map.put("ids",ids); List<Blog> blogs = mapper.conditionQueryForeach(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
list集合中传入几个id就查询出几个人的博客信息