MyBatis传入数组集合类并使用foreach遍历的示例分析

这篇文章将为大家详细讲解有关MyBatis传入数组集合类并使用foreach遍历的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

在mapper中传入数组或集合类,使用foreach标签遍历出其中的值与SQL语句拼接

JAVA dao层接口

public interface UserDao {
  public List<User> getUsersByCollection(Collection collection);
}

mapper文件

<select id="getUsersByCollection" resultMap="userMapper">
  select * from users where id in
  <foreach collection="list" item="id" open="(" close=")" separator=",">
      #{id}
  </foreach> 
</select>

测试

@Test
public void getUsersByCollection() {
  Collection collection = new ArrayList<Integer>();
  collection.add(1);
  collection.add(3);
  collection.add(5);

  List<User> users = userDao.getUsersByCollection(collection);
  System.out.println(users);
}

关于“MyBatis传入数组集合类并使用foreach遍历的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。