[TIL] QueryDsl 사용방법

2024. 8. 6. 00:36·TIL

 

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)

갈 길이 멀다..🤦‍♀️

 

 

 

'TIL' 카테고리의 다른 글

[TIL] 양방향 연관관계 매핑 | Feign client Error Decoder  (0) 2024.08.08
[TIL] Zipkin이란? | Redis란?  (0) 2024.08.06
[TIL] 인증과 인가 | 컨피그 서버 (Spring Cloud Config)  (0) 2024.08.02
[TIL] Java 형변환 | Integer.parseInt와 Integer.valueOf의 차이 | Math.sqrt()와 Math.pow() | 클라이언트 사이드 로드 밸런싱 | 서킷 브레이커 (Resilience4j) | Spring Cloud Gateway  (1) 2024.08.01
[TIL] MSA란? | Spring Cloud란?  (1) 2024.07.31
'TIL' 카테고리의 다른 글
  • [TIL] 양방향 연관관계 매핑 | Feign client Error Decoder
  • [TIL] Zipkin이란? | Redis란?
  • [TIL] 인증과 인가 | 컨피그 서버 (Spring Cloud Config)
  • [TIL] Java 형변환 | Integer.parseInt와 Integer.valueOf의 차이 | Math.sqrt()와 Math.pow() | 클라이언트 사이드 로드 밸런싱 | 서킷 브레이커 (Resilience4j) | Spring Cloud Gateway
dev_ajrqkq
dev_ajrqkq
알고리즘 천재가 될 거야
  • dev_ajrqkq
    기록이 자산이다
    dev_ajrqkq
  • 전체
    오늘
    어제
    • 분류 전체보기 (147)
      • Front-end (0)
      • Back-end (11)
        • Spring (1)
        • Java (8)
      • CS (9)
        • 데이터베이스 (5)
        • 네트워크 (4)
      • Algorithm (80)
      • 이것저것 (0)
      • 버그잡기 (1)
      • TIL (37)
      • 후기 (1)
      • 취준 (0)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      TypeScript
      Til
      개발자취업
      오블완
      코딩테스트준비
      티스토리챌린지
      99클럽
      항해99
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.2
    dev_ajrqkq
    [TIL] QueryDsl 사용방법
    상단으로

    티스토리툴바