简体   繁体   中英

Spring Data JPA: How not to repeat myself in countQueries?

I am using Spring Data JPA repositories (1.7.2) and I am typically facing the following scenario:

  • entities have lazy-loaded collections
  • those collections are sometimes eagerly fetched (via JPAQL fetch join )
  • repositories often return Page<Foo> instead of List<Foo>

I need to provide countQuery to every @Query that uses fetch joins on a repository that returns a Page . This issue has been discussed in this StackOverflow question

My typical repository method looks like this:

@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);

Obviously, it's not very DRY . You can tell that I am repeating all of the conditions in both value and countQuery parameters. How do I stay DRY here?

You could do something like this

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM