// test @Test publicvoidtestFindByIdList()throws Exception { List<Integer> list = newArrayList<Integer>(); list.add(1); list.add(2); List<User> users = userService.findByIdList(list); assertEquals(2, users.size()); }
// service public List<User> findByIdList(List<Integer> list) { return userDao.findByIdList(list); }
// dao List<User> findByIdList(List<Integer> list);
1 2 3 4 5 6
<selectid="findByIdList"resultType="com.mybatis.entity.User"> SELECT * FROM user WHERE id IN <foreachcollection="list"index="index"item="item"open="("separator=","close=")"> #{item} </foreach> </select>
// service public List<User> findByIdArray(Integer[] ids) { return userDao.findByIdArray(ids); }
// dao List<User> findByIdArray(Integer[] ids);
1 2 3 4 5 6
<selectid="findByIdArray"resultType="com.mybatis.entity.User"> SELECT * FROM user WHERE id IN <foreachcollection="array"index="index"item="item"open="("separator=","close=")"> #{item} </foreach> </select>
// test @Test publicvoidfindByIdSet()throws Exception { Set<Integer> set = newHashSet<Integer>(); set.add(1); set.add(2); List<User> users = userService.findByIdSet(set); assertEquals(2, users.size()); }
// service public List<User> findByIdSet(Set<Integer> set) { return userDao.findByIdSet(set); }
// dao List<User> findByIdSet(Set<Integer> set);
1 2 3 4 5 6
<selectid="findByIdSet"resultType="com.mybatis.entity.User"> SELECT * FROM user WHERE id IN <foreachcollection="collection"index="index"item="item"open="("separator=","close=")"> #{item} </foreach> </select>
<selectid="findByMapForeach"resultType="com.mybatis.entity.User"> SELECT * FROM user WHERE name = #{name} AND id IN <foreachcollection="ids"index="index"item="item"open="("separator=","close=")"> #{item} </foreach> </select>
@Param
传入的参数使用的@Param注解,collection的属性值为注解的名称
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// test @Test publicvoidfindByIdListAnnotation()throws Exception { List<Integer> list = newArrayList<Integer>(); list.add(1); list.add(2); List<User> users = userService.findByIdListAnnotation(list); assertEquals(2, users.size()); }
// service public List<User> findByIdListAnnotation(List<Integer> list) { return userDao.findByIdListAnnotation(list); }
// dao List<User> findByIdListAnnotation(@Param("annotatedList") List<Integer> list);
1 2 3 4 5 6
<selectid="findByIdListAnnotation"resultType="com.mybatis.entity.User"> SELECT * FROM user WHERE id IN <foreachcollection="annotatedList"index="index"item="item"open="("separator=","close=")"> #{item} </foreach> </select>