QueryDSL

  • spring data jpa는 두 가지 방법으로 QueryDSL를 지원한다.
    • org.springframework.data.querydsl.QueryDslPredicateExecutor
    • org.springframework.data.querydsl.QueryDslRepositorySupport

1. QueryDslPredicateExecutor을 상속 받는 식이다.

public interface ItemRepository extends JpaRepository<Item, Long>, QueryDslPredicateExecutor<Item> {
    
}

itemRepository.findAll(item.name.contains("장난감").and(item.price.between(10000, 20000)));
  • QueryDSL를 검색 조건으로 사용할 수 있다.
  • 그러나 한계가 있다. join, fetch를 사용할 수 없다(JPQL 묵시적 종린은 가능)

2. QueryDslRepositorySupport 사용

  • JPAQuery 객체를 생성해서 사용하면 된다.
  • QueryDslRepositorySupport를 상속 받으면 더 편하게 사용할 수 있다. ```java

@Repository public abstract class QuerydslRepositorySupport { private final PathBuilder<?> builder; @Nullable private EntityManager entityManager; @Nullable private Querydsl querydsl;

public QuerydslRepositorySupport(Class<?> domainClass) {
    Assert.notNull(domainClass, "Domain class must not be null");
    this.builder = (new PathBuilderFactory()).create(domainClass);
}

@Autowired
public void setEntityManager(EntityManager entityManager) {
    Assert.notNull(entityManager, "EntityManager must not be null");
    this.querydsl = new Querydsl(entityManager, this.builder);
    this.entityManager = entityManager;
}

@PostConstruct
public void validate() {
    Assert.notNull(this.entityManager, "EntityManager must not be null");
    Assert.notNull(this.querydsl, "Querydsl must not be null");
}

@Nullable
protected EntityManager getEntityManager() {
    return this.entityManager;
}

protected JPQLQuery<Object> from(EntityPath<?>... paths) {
    return this.getRequiredQuerydsl().createQuery(paths);
}

protected <T> JPQLQuery<T> from(EntityPath<T> path) {
    return this.getRequiredQuerydsl().createQuery(new EntityPath[]{path}).select(path);
}

protected DeleteClause<JPADeleteClause> delete(EntityPath<?> path) {
    return new JPADeleteClause(this.getRequiredEntityManager(), path);
}

protected UpdateClause<JPAUpdateClause> update(EntityPath<?> path) {
    return new JPAUpdateClause(this.getRequiredEntityManager(), path);
}

protected <T> PathBuilder<T> getBuilder() {
    return this.builder;
}

@Nullable
protected Querydsl getQuerydsl() {
    return this.querydsl;
}

private Querydsl getRequiredQuerydsl() {
    if (this.querydsl == null) {
        throw new IllegalStateException("Querydsl is null");
    } else {
        return this.querydsl;
    }
}

private EntityManager getRequiredEntityManager() {
    if (this.entityManager == null) {
        throw new IllegalStateException("EntityManager is null");
    } else {
        return this.entityManager;
    }
} }

```