IN() 절 처리
2024. 11. 7. 22:47ㆍJava/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}
'Java > mybatis' 카테고리의 다른 글
Mybatis insert후 키값 반환하기 (0) | 2024.12.27 |
---|---|
Mybatis if ~ else 적용하기 (0) | 2024.11.27 |
mybatis ORA-00979: GROUP BY 표현식이 아닙니다 (0) | 2024.11.26 |
mybatis를 이용해서 BLOB 저장 (1) | 2024.11.07 |
Spring boot mybatis 환경파일 설정 (0) | 2024.08.14 |