我正在使用Spring Data JPA存储库(1.7.2),我通常面临以下情况:
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);
显然,它不是很干。您可以告诉我,我正在重复value
和countQuery
参数中的所有条件。我如何在这里待干?
答案 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);