IN() 절 처리

2024. 11. 7. 22:47Java/mybatis

데이터

XML

<!-- File: UserMapper.xml -->
<select id="selectUsersByNames" parameterType="map" resultType="hashmap">
    SELECT id, name, age
    FROM users
    WHERE name IN
    <foreach item="name" collection="nameList" open="(" separator="," close=")">
        #{name}
    </foreach>
</select>

Java

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserService {
    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public List<Map<String, Object>> getUsersByNames(List<String> nameList) {
        // Create a parameter map for MyBatis
        Map<String, Object> params = new HashMap<>();
        params.put("nameList", nameList);
        
        // Call the MyBatis mapper to execute the query
        return userMapper.selectUsersByNames(params);
    }
}

Mapper Interface

import java.util.List;
import java.util.Map;

public interface UserMapper {
    List<Map<String, Object>> selectUsersByNames(Map<String, Object> params);
}

Main

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        UserService userService = new UserService(userMapper);
        
        // Sample list of names to search for
        List<String> names = Arrays.asList("Alice", "Charlie", "Eve");
        
        // Retrieve users with specified names
        List<Map<String, Object>> users = userService.getUsersByNames(names);
        
        // Print the result
        users.forEach(System.out::println);
    }
}

결과

{id=1, name=Alice, age=25}
{id=3, name=Charlie, age=35}
{id=5, name=Eve, age=45}