MSA프로젝트 실습 관련 강의를 보던 중 QueryDSL에 대해 강사님이 말하시는데 첨 듣는거라 당황했다... 아무래도 JPA를 잘몰라서 그런듯 ㅜㅜ
앞으로의 프로젝트를 위해 알고가면 좋다고 말씀하셔서 QueryDSL이 뭔지 찾아보게 되었다.
DSL (Domain-Specific-Languages)
특정 도메인에서 발생하는 문제를 효과적으로 해결하기 위해 설계된 언어
SQL 형식의 쿼리를 Type-Safe 하게 생성할 수 있도록 하는 DSL을 제공하는 라이브러리
Querydsl - jpa 의존성 추가
implementation "com.querydsl:querydsl-jpa:5.0.0:jakarta"
QClass 생성을 위한 annotationProcesser 추가
annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jakarta"
annotationProcessor "jakarta.annotation:jakarta.annotation-api"
annotationProcessor "jakarta.persistence:jakarta.persistence-api"
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private int age;
// getters and setters
}
QUser 클래스
QUser 클래스는 JPA에서 자동 생성되며, QueryDSL을 사용하여 User 엔티티에 대한 메타데이터를 제공한다.
QUser.user로 참조할 수 있다.
쿼리DSL로 쿼리 작성하기
쿼리DSL로 User 테이블에서 age가 19이상인 사용자를 조회하는 쿼리를 작성해보면
@Autowired
private EntityManager entityManager;
public List<User> findUsers() {
JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);
QUser qUser = QUser.user;
List<User> users = queryFactory
.selectFrom(qUser)
.where(qUser.age.goe(19))
.fetch();
return users;
}
이렇게 하면 age가 19세 이상인 사용자만 조회됩니다.
즉, 쿼리DSL을 사용하여 SQL을 작성하지 않고도 데이터를 조회할 수 있습니다.
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
@Component
public class ProductServiceApplicationQueryDslConfig {
@Bean
JPAQueryFactory jpaQueryFactory(EntityManager em){
return new JPAQueryFactory(em);
}
}
public interface ProductRepositoryCustom {
Page<ProductResponseDto> searchProducts(ProductSearchDto searchDto, Pageable pageable);
}
@RequiredArgsConstructor
public class ProductRepositoryImpl implements ProductRepositoryCustom{
private final JPAQueryFactory queryFactory;
@Override
public Page<ProductResponseDto> searchProducts(ProductSearchDto searchDto, Pageable pageable) {
return /* querydsl 코드 */
}
@Repository
public interface ProductRepository extends JpaRepository<Product, Long>, ProductRepositoryCustom {
}
장점
단점
QueryDSL의 사용법과 장단점, 그리고 어떻게 활용할 수 있는지에 대해 이해했으니
JOIN, GROUP BY, HAVING, ORDER BY 같은 SQL의 다양한 기능과 페이지네이션도 QueryDSL로 하는 법에 대해 더 공부해봐야겠다.. 😂