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);
}

猜你喜欢

转载自www.cnblogs.com/esrevinud/p/12299195.html
今日推荐