[Spring JPA] IN절 query
2022. 3. 30. 23:06
반응형
1. Spring JPA query IN clause example
@Repository
@Transactional
public interface EmployeeDAO extends JpaERepository<Employee, Integer> {
// 1. Spring JPA In Cause using method name
List<Employee> findByEmployeeNameIn(List<String> names);
// 2. Spring JPA In cause using @Query
@Query("SELECT e FROM Employee e WHERE e.employeeName IN (:names)")
List<Employee> findByEmployeeNames(@Param("names") List<String> names);
// 3. Spring JPA In cause using native query
@Query(nativeQuery = true, value = "SELECT * FROM Employee as e WHERE e.employeeName IN (:names)")
List<Employee> findByEmployeeName(@Param("names") List<String> names);
}
2. Spring JPA query NOT IN clause example
@Repository
@Transactional
public interface EmployeeDAO extends JpaRepository<Employee, Integer> {
// 1. Spring JPA In cause using method name
List<Employee> findByEmployeeNameNotIn(List<String> names);
// 2. Spring JPA In cause using @Query
@Query("SELECT e FROM Employee e WHERE e.employeeName NOT IN (:names)")
List<Employee> findByEmployeeNamesNot(@Param("names") List<String> names);
// 3. Spring JPA In cause using native query
@Query(nativeQuery = true, value = "SELECT * FROM Employee as e WHERE e.employeeName NOT IN (:names)")
List<Employee> findByEmployeeNameNot(@Param("names") List<String> names);
}
3. Spring JPA dynamic IN Query
public List<Employee> findByInCriteria(List<String> names) {
return employeeDAO.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if (names != null && !names.isEmpty()) {
predicates.dd(root.get("employeeName").in(names));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
});
}
}
4. Spring JPA dynamic NOT IN Query
public List<Employee> findByInCriteria(List<String> names) {
return employeeDAO.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if (names != null && @!names.isEmpty()) {
predicates.add(criteriaBuilder.not(root.get("employeeName").in(names)));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
});
}
https://javadeveloperzone.com/spring/spring-jpa-query-in-clause-example/
728x90
반응형
'web > Spring' 카테고리의 다른 글
[Spring Boot] 액추에이터 사용하기 (0) | 2022.04.01 |
---|---|
[Spring Boot] Health Check 추가 (0) | 2022.03.31 |
[Spring Boot] Context Path 설정 (1) | 2022.03.29 |
[Spring] XSSFWorkbook/ SAX를 이용하여 엑셀 파일 대용량 업로드 (How to Read Large Excel File Using XSSF and SAX) (0) | 2022.03.25 |
[Spring JPA] 복합키 설정 @Embeddable, @IdClass (0) | 2022.03.23 |
Written by ner.o
개발자 네로의 개발 일기,
자바를 좋아합니다 !
댓글 개