Spring Data JPA:如何在countQueries中重复自己?

时间:2015-02-18 11:10:57

标签: java spring jpa spring-data

我正在使用Spring Data JPA存储库(1.7.2),我通常面临以下情况:

  • 实体具有延迟加载的集合
  • 这些集合有时急切地获取(通过JPAQL fetch join
  • 存储库通常会返回Page<Foo>而不是List<Foo>

我需要向每个countQuery提供@Query,它在返回Page的存储库上使用获取连接。 this StackOverflow question

中已讨论过此问题

我的典型存储库方法如下所示:

@Query(value = "SELECT e FROM Employee e LEFT JOIN FETCH e.addresses a " +
    "WHERE e.company.id = :companyId " +
    "AND e.deleted = false " +
    "AND e.primaryAddress.deleted = false " +
    "ORDER BY e.id, a.id",
    countQuery="SELECT count(e) FROM Employee e WHERE e.companyId = :companyId AND e.deleted = false AND e.primaryAddress.deleted = false"
)
Page<Employee> findAllEmployeesWithAddressesForCompany(@Param("companyId") long companyId, Pageable pageable);

显然,它不是很干。您可以告诉我,我正在重复valuecountQuery参数中的所有条件。我如何在这里待干?

1 个答案:

答案 0 :(得分:3)

你可以做这样的事情

public interface MyRepository extends JpaRepository {

    public static final String WHERE_PART = "e.companyId = :companyId AND e.deleted = false AND e.primaryAddress.deleted = false ";

    @Query(value = "SELECT e FROM Employee e LEFT JOIN FETCH e.addresses a " +
        "WHERE " + MyRepository.WHERE_PART
        "ORDER BY e.id, a.id",
        countQuery="SELECT count(e) FROM Employee e WHERE " + MyRepository.WHERE_PART
    )
    Page<Employee> findAllEmployeesWithAddressesForCompany(@Param("companyId") long companyId, Pageable pageable);