If you want to paginate the query results of a JPA criteria query, you have to call the findAll(Specification s, Pageable p) method that is declared by the JpaSpecificationExecutor interface. The implementation of this method uses the provided Specification for two purposes: It gets the count of the matching entities and the actual entities.
This approach works fine in most of the cases. However, if you have to join a lazily fetched collection of the entity, a following exception is thrown (when Hibernate is used as JPA provider):
org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
In this case, the following query is created:
select count(*) from foo.bar.Person as generatedAlias0
left join fetch generatedAlias0.pets as generatedAlias1 where
As the exception explained, the problem is that the Person is not present in the select list of the count query.
In this case it would useful if you could manually specify the specification that is used to create the count query. This way you create two specifications: the first one would be used to create the count query (no join needed) and the second one would fetch the actual data (joins can be used)
7 votes, 10 watchers
The text was updated successfully, but these errors were encountered:
I'd like to add another situation where this feature would really help. At my company we use MS SQL Server. This RDBMS does not support a combination of DISTINCT and ORDER BY sufficiently to support all of our business logic. We use Specifications to programmatically generate queries using GROUP BY clauses to eliminate duplicate records where DISTINCT would typically be used. However, Spring Data JPA does not correctly calculate countQueries in this case. If I could provide a count query Specification, I could ensure that the correct corresponding count was calculated.
I'd be available to help work on this enhancement given a little guidance from the project team as to how they wanted the feature implemented. I don't believe the work is too complex once an API is decided upon