How to use an IN clause with a List in Mybatis?

Using the “in” clause with a List in MyBatis can be achieved by using the foreach tag in dynamic SQL. Below is a simple example:

Suppose there is a User class and a UserMapper interface that need to retrieve user information based on a list of user IDs.

public interface UserMapper {
    List<User> selectUsersByIdList(@Param("idList") List<Integer> idList);
}

You can use the foreach tag in the corresponding UserMapper.xml file to achieve this.

<select id="selectUsersByIdList" resultType="User">
    SELECT * FROM user WHERE id IN
    <foreach collection="idList" item="id" open="(" separator="," close=")">
        #{id}
    </foreach>
</select>

In this example, idList is a passed List, the foreach tag will iterate through each element in idList and concatenate it to the IN condition in the SQL statement.

Example of usage:

List<Integer> idList = Arrays.asList(1, 2, 3);
List<User> users = userMapper.selectUsersByIdList(idList);

This allows you to query user information by passing in a List through “in”.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds