首页 > 解决方案 > 如何在 JPA 中找到与规范和可分页关系密切的所有内容?

问题描述

我反对多对多的关系productkind我可以通过以下方式获得具有热切关系的产品:

  @Query(
    value = "select distinct product from Product product left join fetch product.kinds",
    countQuery = "select count(distinct product) from Product product"
  )
  Page<Product> findAllWithEagerRelationships(Pageable pageable);

或按规格和可分页的产品:

  @Transactional(readOnly = true)
  public Page<Product> findByCriteria(ProductCriteria criteria, Pageable page) {
    log.debug("find by criteria : {}, page: {}", criteria, page);
    final Specification<Product> specification = createSpecification(criteria);
    return productRepository.findAll(specification, page);
  }

但是当我尝试将它们合二为一时,

  @Query(
    value = "select distinct product from Product product left join fetch product.kinds",
    countQuery = "select count(distinct product) from Product product"
  )
  Page<Product> findAll(Specification<Product> specification, Pageable pageable);

我收到错误:

Caused by: org.hibernate.HibernateException: firstResult/maxResults specified with collection fetch. In memory pagination was about to be applied. Failing because 'Fail on pagination over collection fetch' is enabled.

所以我该怎么做?

标签: javaspringspring-bootjpaspring-data-jpa

解决方案


我找到了临时解决方案。我将@ManyToMany实体类中的注释更改为

  @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE })

然后我的代码工作异常。如果你想试试这个。但我不确定这个解决方案的性能。我需要确认一下。

更新:此解决方案可以解决加载数据问题,但我将无法编辑数据


推荐阅读