TIL

[TIL] QueryDsl 사용방법

dev_ajrqkq 2024. 8. 6. 00:36

 

8/5 진행사항

✅ 알고리즘 2문제

✅ MSA 강의 1-12

 

QueryDsl 사용방법

 

dependencies {
	// queryDSL
	implementation "com.querydsl:querydsl-jpa:${querydslVersion}:jakarta"
	annotationProcessor "com.querydsl:querydsl-apt:${querydslVersion}:jakarta"
 	annotationProcessor "jakarta.annotation:jakarta.annotation-api"
	annotationProcessor "jakarta.persistence:jakarta.persistence-api"
 }
 
def querydslSrcDir='src/main/generated'
clean{
	delete file(querydslSrcDir)
}

build.gradle에 의존성 추가

 

QueryDsl은 프로젝트 내의 @Entity 어노테이션을 선언한 클래스를 탐색하고 Q클래스를 생성한다.

 

Entity 파일을 생성 후

Tasks > other > compileJava로 자바를 빌드한다.

build 디렉토리 아래 Q가 붙은 클래스 파일이 생성 되었다.

이러한 클래스를 Q클래스라고 하고 Q클래스를 통해 Type-Safe한 쿼리 작성이 가능하다.

 

그렇다면 Type-Safe 하다는 건 뭘까?

'타입에 안정적이다' 라는 것은 타입 판별(Type Check)이 가능하여 컴파일시 문제를 잡을 수 있는 것을 말한다.

 

일반적인 sql을 사용하면 type check가 불가능하고 실행 전까지 에러여부를 알 수 없다(런타임 시 에러 발견 가능).

 

QueryDsl은 JPAQueryFactory라는 클래스로 쿼리 작성을 한다.

@Component
public class ProductQueryDslConfig {
    @Bean
    JPAQueryFactory jpaQueryFactory(EntityManager em) {
        return new JPAQueryFactory(em);
    }
}

위와 같이 빈등록을 한 후 사용해준다.

이 클래스를 사용하여 쿼리를 짜면 자동완성 기능을 제공받을 수 있고

자바코드로 쿼리를 작성하기 때문에 컴파일 시점에 에러 발견이 가능하다.

 

결국, 일반적인 sql보다 더 안정적인 쿼리를 짤 수 있게 만든 것이 QueryDsl이라고 생각하면 될 거 같다.

 

public interface ProductRepository extends JpaRepository<Product, Long>,ProductRepositoryCustom {
}

기존 JpaRepository를 상속하는 인터페이스에 custom repository를 추가 상속한다.

 

public interface ProductRepositoryCustom {
    Page<ProductResponseDto> searchProducts(ProductSearchDto searchDto, Pageable pageable);
}

custom repository 생성

@RequiredArgsConstructor
public class ProductRepositoryImpl implements ProductRepositoryCustom {

    private final JPAQueryFactory queryFactory;
    
    ...
    
 }

앞에서 생성한 custom repository 구현 클래스이다.

해당 구현 클래스 이름은 Impl로 끝나야 한다.

 

querydsl 메소드 관련해서는 다음에 추가해보도록 하겠다.

 

오늘의 tmi)

갈 길이 멀다..🤦‍♀️