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 | 31 |
Tags
- spring JPA DB multi Connection
- JAVA Exception 종류
- Spring
- repository annotation
- Transactions Propagation Option
- AllArgsConstructor
- NoArgsConstructor
- Data Annotation
- spring JPA DB Connection
- JPA DB Connection 다중
- vuecomponent
- @Builder @NoArgsConstructor
- JpaRepository update
- mapper annotationo
- 자바버그수정
- docker 로그
- JPA DB 다중 Connection
- vueslot
- Vue
- spring mapper annotation
- spring mapper
- spring repository
- spring @mapper
- 도커 컨테이너 로그
- CrudRepository update
- doker logs tail
- 도커 로그 확인
- Spring JPA Specification
- 도커 logs
- spring DB Connection
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을 사용하는 습관을 들여봐야겠다.