Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- spring @mapper
- docker 로그
- vuecomponent
- 도커 로그 확인
- Spring JPA Specification
- @Builder @NoArgsConstructor
- mapper annotationo
- NoArgsConstructor
- spring DB Connection
- Spring
- JpaRepository update
- 도커 logs
- CrudRepository update
- spring mapper annotation
- JPA DB 다중 Connection
- JPA DB Connection 다중
- AllArgsConstructor
- spring JPA DB multi Connection
- spring mapper
- vueslot
- spring JPA DB Connection
- JAVA Exception 종류
- Vue
- Data Annotation
- repository annotation
- doker logs tail
- spring repository
- Transactions Propagation Option
- 도커 컨테이너 로그
- 자바버그수정
Archives
- Today
- Total
개발을 잘하고 싶은 개발자
[Spring JPA] Specification으로 쿼리 조건 처리하기 본문
JPA를 사용하면서 까다로운 쿼리를 처리하는데 종종 어려움이 있다.
이 때 "Specification"의 도움을 받아 동적쿼리(Dynamic Query)로 처리할 수 있다
참고 페이지
https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
https://dahye-jeong.gitbook.io/spring/spring/2020-04-12-jpa-specification
- JpaSpecificationExecutor을 extends 해준다.
Specification을 입력 받도록 Repository 인터페이스 정의하기
public interface PostRepository
extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
}
- 검색 조건을 모아 놓은 클래스 만들기 (Specifications 객체)
public class PostSpecs {
public static Specification<Post> withTitle(String title) {
return (Specification<Post>) ((root, query, builder) ->
builder.equal(root.get("title"), title)
);
}
}
- 검색 조건을 조합한 Specification 인스턴스를 이용해서 검색하기
@GetMapping("/post/list")
public List<Post> getPostList(@RequestParam(required = false) String title,
@RequestParam(required = false) String tag,
@RequestParam(required = false) Integer likes) {
if (title != null) {
return postRepository.findAll(PostSpecs.withTitle(title));
} else if (...) {
...
}
}
간단해보이지만 어렵고
생각보다 엄청 많은 기능을 제공하기 때문에 더 공부하고 실제 소스에 녹여봐야 내것이 될 것 같다.
이 Specification을 몰랐을 때에는 귀찮고, 쉬운 길을 찾아 직접 @Query 어노테이션을 사용해서 쿼리를 작성했었다.
이제는 특수한 상황을 제외하고는 되도록 Specification을 사용하는 습관을 들여봐야겠다.