implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta'
annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jakarta"
annotationProcessor "jakarta.annotation:jakarta.annotation-api"
annotationProcessor "jakarta.persistence:jakarta.persistence-api"
spring 3.x 버전부터는 다음과 같이 build.gradle에 추가해주면 된다.
의존성을 추가해주면 하단 사진과 같은 Q객체들이 생성된다.
사용 방식은 대표적으로 두가지이다.
1. Custom 인터페이스를 만들어 사용하는 방식
public interface CommentRepositoryCustom {
Page<Comment> findAllByPostTimeBetween(Pageable pageable, LocalDateTime startOfDay, LocalDateTime endOfDay, String sort);
Optional<Comment> findCommentsByAuthorAndDate(String phoneNumber, LocalDateTime startOfDay, LocalDateTime endOfDay);
List<Comment> findTop10CommentsByPostTimeBetweenOrderByLikeCountDescIdAsc(LocalDateTime startOfDay, LocalDateTime endOfDay);
}
위와 같이 Custom 인터페이스를 직접 만들어 구현할 메서드들을 먼저 정의한다.
import static softeer.team_pineapple_be.domain.comment.domain.QComment.comment; //Q객체 사용을 위한 임포트
@Repository
@RequiredArgsConstructor
public class CommentRepositoryImpl implements CommentRepositoryCustom {
private final JPAQueryFactory queryFactory;
이를 상속받은 구현체를 만든다. 이 때 쿼리를 직접 만들기 위하여 JPAQueryFactory를 주입한다. 또한 Q객체 사용을 위해 이를 import한다.
public interface CommentRepository extends JpaRepository<Comment, Long>, CommentRepositoryCustom
최종적으로 원래의 레포지토리 인터페이스에 상속받음으로써 사용된다.
2. DAO를 만들어 사용하는 방식
DAO란 Data Access Object의 약자로 데이터베이스의 data에 접근하기 위한 객체이며 데이터베이스 접근을 하기 위한 로직과 비즈니스 로직을 분리하기 위하여 사용된다.
@Repository
@RequiredArgsConstructor
public class CommentDao {
private final JPAQueryFactory queryFactory;
다음과 같이 직접 클래스를 만들어 사용하고자하는 메서드를 구현해주면 된다. 이후 서비스 로직에서 직접 의존성을 주입하여 사용하면 된다.
클래스를 여러개 구현할 필요 없이 직접 DAO를 사용하면 되기에 사용이 간편하다는 장점이 있다. 다만 이전에 JPA만을 통해 구현되어 있다면 service로직에서도 바꿔줘야 할 것이 있기 때문에 1번 방법을 사용하는 방식도 완전히 나쁜 방법만은 아닌 것 같다.
'DB > Querydsl' 카테고리의 다른 글
[Querydsl] Querydsl이란? (0) | 2024.09.02 |
---|