처음으로 Querydsl 써 본 기념으로 쓰는 블로그!
에러가 너무 많이 나서 헷갈렸다,,,최근에 Spring Boot 3.0 으로 넘어온 뒤로 환경 설정하는게 여러가지 바뀐 듯 ㅠㅠ
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"
dependencies에 위와 같이 4개를 추가해줬다.
참고로 내 스프링 부트 버전은 3.1.5
@Configuration
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = "asac.coupang")
public class JPAConfig {
@PersistenceContext
private EntityManager entityManager;
@Bean
public JPAQueryFactory queryFactory(){
return new JPAQueryFactory(entityManager);
}
}
다음과 같은 Config파일을 설정해주었다.
이 과정은 해당 프로젝트 어디에서든 JpaQueryFactory를 주입받아 Querydsl을 사용할 수 있게 해준다.
Querydsl 사용방법 3가지
1. QuerydslRepositorySupport와 JpaRepository 각각 사용
2. JpaRepository에서 Querydsl 사용 가능하도록 설정하여 사용 ⭐😎
3. 상속없이 Querydsl 사용
난 2번 방법을 사용해서 구현했다!
나머지는 아직 모르니까,,,일단 2번에 대해서 설명하겠음
일단 내가 구현한 것은 Product Entity에 대해서 전체 Entity를 불러오는 것과 Category에 해당하는 Entity들만 불러오는 2개의 API이다.
이를 위해 추가적으로 생성한 Repository는
총 3개이다.
ProductRepository.java
는 아래와 같고 따로 바뀐 수정 사항은
ProductRepositoryCustom을 추가적으로 extends 해주었다는 점!
public interface ProductRepository extends JpaRepository<Product, Long>, ProductRepositoryCustom {
@Query("SELECT p FROM Product p WHERE p.category = :category")
List<Product> findByCategory(@Param("category") Category category);
}
ProductRepositoryCustom.java
는 아래와 같고,
내가 구현할 함수명들을 선언만 해놓았다!
public interface ProductRepositoryCustom {
List<Product> findBySeller(Seller seller);
List<Product> findAll();
}
ProductRepositoryImpl.java
는 위에서 선언한 함수들을 직접 Querydsl로 구현해놓은 중요한 코드이다.
@Repository
@RequiredArgsConstructor
public class ProductRepositoryImpl implements ProductRepositoryCustom {
private final JPAQueryFactory jpaQueryFactory;
@Override
public List<Product> findBySeller(Seller seller) {
return jpaQueryFactory.selectFrom(product)
.where(
product.seller.eq(seller)
)
.fetch();
}
@Override
public List<Product> findAll() {
return jpaQueryFactory.selectFrom(product)
.fetch();
}
}
대충 Jpa와는 조금 다른 것을 실감할 수 있다.
생각보다 편해보여서 다음부터 애용할지도...?
사실 잘 모르겠지만 테스트 결과 아래와 같이 정상적으로 동작하는 것을 확인했다.
참고 문헌
https://squirmm.tistory.com/entry/SpringBoot-Querydsl-설정
https://squirmm.tistory.com/entry/SpringBoot-Querydsl-사용방법?category=1018066