스프링데이터 + JPA/QueryDSL

37. Querydsl 리포지토리 지원

sdafdq 2023. 12. 4. 11:17

이거는, Querydsl을 사용한 리포지토리를 만들 때, 상속받아서 쓰면 약간 편리한? 그런 거다.

@Repository
public abstract class QuerydslRepositorySupport {

    private final PathBuilder<?> builder;

    private @Nullable EntityManager entityManager;
    private @Nullable 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, builder);
       this.entityManager = entityManager;
    }

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

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

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

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

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

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

    @SuppressWarnings("unchecked")
    protected <T> PathBuilder<T> getBuilder() {
       return (PathBuilder<T>) builder;
    }

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

    private Querydsl getRequiredQuerydsl() {

       if (querydsl == null) {
          throw new IllegalStateException("Querydsl is null");
       }

       return querydsl;
    }

    private EntityManager getRequiredEntityManager() {

       if (entityManager == null) {
          throw new IllegalStateException("EntityManager is null");
       }

       return entityManager;
    }
}

이 가상클래스를 상속받는거다.

 

EntityManager 등을 알아서 받아준다.