在Query DSL + Spring Data JPA中分组抛出NoSuchElementException

时间:2017-09-27 10:44:09

标签: java spring spring-boot spring-data-jpa querydsl

我正在尝试使用Spring Data JPA和Query DSL执行逐个查询。

但是,我得到以下例外: -

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'japanWHTDaoImpl': 
   Unsatisfied dependency expressed through field 'wht21940000DataRepo'; 
       nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'japanWHT21940000DataRepository': 
    Invocation of init method failed; nested exception is java.util.NoSuchElementException

我尝试编写自定义存储库实现并在我的接口和impl类下面提供:

自定义界面:

public interface JapanWHT21940000DataRepositoryCustom {
        List<WHT21940000Royalties> findLocalCcyAmtsByRemarks();
}

自定义Impl类:

@Repository
@Transactional
public class JapanWHT21940000DataRepositoryCustomImpl extends QueryDslRepositorySupport implements JapanWHT21940000DataRepositoryCustom {

    public JapanWHT21940000DataRepositoryCustomImpl(Class<?> domainClass) {
    super(domainClass);
    // TODO Auto-generated constructor stub
    }

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<WHT21940000Royalties> findLocalCcyAmtsByRemarks() {
    QWHT21940000Data wht21940000Data = QWHT21940000Data.wHT21940000Data;
    JPAQuery<WHT21940000Royalties> query = new JPAQuery<WHT21940000Royalties>(entityManager);
    query.from(wht21940000Data).groupBy(wht21940000Data.remarks).select(wht21940000Data.remarks, wht21940000Data.localCcyAmt.sum());

    return null;
    }

}

Spring数据JPA界面:

public interface JapanWHT21940000DataRepository
    extends JpaRepository<WHT21940000Data, Long>, 
        QueryDslPredicateExecutor<WHT21940000Data>, 
        JapanWHT21940000DataRepositoryCustom {

}

和DAO课程:

@Repository
@Transactional("japanWhtTransactionManager")
public class JapanWHTDaoImpl implements JapanWHTDao {
    @Autowired
    JapanWHT21940000DataRepository wht21940000DataRepo;
    // more code to follow...

编辑:或者,在Spring数据JPA +查询DSL中进行逐组查询的方式是否比我正在尝试的更简单,更好的方式?

1 个答案:

答案 0 :(得分:0)

我认为真正的问题是从JpaRepositories执行自定义querydsl查询,但我必须建议使用自定义扩展基础存储库类,如下所示。

首先,扩展基础存储库类。

@NoRepositoryBean
public interface ExtendedQueryDslJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {

    <T1> Page<T1> findAll(JPQLQuery jpqlQuery, Pageable pageable);
}

相关实施。

public class ExtendedQueryDslJpaRepositoryImpl<T, ID extends Serializable>
    extends QueryDslJpaRepository<T, ID> implements ExtendedQueryDslJpaRepository<T, ID> {

    private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;

    private final EntityPath<T> path;
    private final PathBuilder<T> builder;
    private final Querydsl querydsl;

    private EntityManager entityManager;

    public ExtendedQueryDslJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
        this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER);
    }

    public ExtendedQueryDslJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager, EntityPathResolver
        resolver) {

        super(entityInformation, entityManager);
        this.path = resolver.createPath(entityInformation.getJavaType());
        this.builder = new PathBuilder(this.path.getType(), this.path.getMetadata());
        this.querydsl = new Querydsl(entityManager, this.builder);
        this.entityManager = entityManager;
    }

    @Override
    public <T1> Page<T1> findAll(JPQLQuery jpqlQuery, Pageable pageable) {

        final JPQLQuery<?> countQuery = jpqlQuery;

        JPQLQuery<T1> query = querydsl.applyPagination(pageable, jpqlQuery);

        return PageableExecutionUtils.getPage(query.fetch(), pageable, countQuery::fetchCount);
    }
}

上述类可以放在配置包中。

然后,我们将ExtendedQueryDslJpaRepositoryImpl定义为JpaRepository类应扩展的默认类,如下所示:

@Configuration
@EnableJpaRepositories(basePackageClasses = Application.class, repositoryBaseClass = ExtendedQueryDslJpaRepositoryImpl.class)
public class JpaConfig {

    @PersistenceContext
    private EntityManager entityManager;

    @Bean
    public JPAQueryFactory jpaQueryFactory() {
        return new JPAQueryFactory(entityManager);
    }
}

下一步是为应用程序的Entity定义存储库,例如。 CustomEntity

public interface CustomRepository extends ExtendedQueryDslJpaRepository<CustomEntity, Long>, CustomRepositorySupport {
}

接下来,我们为自定义方法定义定义接口CustomRepositorySupport

public interface CustomRepositorySupport {

    JPQLQuery<CustomListDto> createCustomIndexQuery();
}

最后是自定义存储库实现。

@Repository
public class CustomRepositoryImpl implements CustomRepositorySupport {

    private JPAQueryFactory queryFactory;

    @Autowired
    public CustomRepositoryImpl(JPAQueryFactory queryFactory) {
        this.queryFactory = queryFactory;
    }

    @Override
    public JPQLQuery<CustomListDto> createCustomIndexQuery() {

        QCustomEntity qCustomEntity = QCustomEntity.customEntity;

        BooleanBuilder predicate = new BooleanBuilder();

        // Create predicate as desired
        // predicate.and(...);

        // Create projection of fields
        /* FactoryExpression<CustomListDto> factoryExpression = Projections.bean(CustomListDto.class,
            qCustomEntity.fieldA,
            qCustomEntity.fieldB,
            qCustomEntity.fieldC,
            qCustomEntity.fieldD,
            qCustomEntity.fieldE,
            qCustomEntity.fieldF); */

        return queryFactory.from(qCustomEntity).select(factoryExpression).where(predicate);
    }
}

最后一步是从Service类实际调用该方法,如下所示。

public interface CustomFinder {

    Page<CustomListDto> findIndex(Pageable pageable);
}

-

@Service
public class CustomFinderImpl implements CustomFinder {

    private CustomRepository customRepository;

    @Autowired
    public CustomFinderImpl(CustomRepository customRepository) {
        this.customRepository = customRepository;
    }

    @Override
    public Page<CustomListDto> findIndex(Pageable pageable) {

        JPQLQuery<CustomListDto> query = customRepository.createCustomIndexQuery();

        return customRepository.findAll(query, pageable);
    }
}

与我们实施public <T1> List<T1> findAll(JPQLQuery query, FactoryExpression<T1> factoryExpression)的方式相同,我们可以简单地将所需的方法实现为public <T1> List<T1> findAll(JPQLQuery query, FactoryExpression<T1> factoryExpression)<T1> List<T1> findList(JPQLQuery query, FactoryExpression<T1> factoryExpression)等。

这样,我们为所有存储库添加功能,以便利用所有类型的查询查询,而不仅仅是group byprojections

看起来有点过于复杂,但是如果你选择实现它,看看它是如何运作的,你就会坚持下去。它在真实应用程序中成功使用,提供对投影查询的访问(无需加载不需要的完整实体),分页查询,存在子查询等。

最后,使用一种中央基础存储库类是一种只能编写一次的可重用代码。

希望有所帮助。