1. You get this warning because Hibernate must make sure that the pagination is done against parents. If you execute the plain SQL you'd see that the parent row info is duplicated for each joined child record referencing the parent. For this reason, Hibernate cannot simply truncate the Resultset after N entries because it would mean that the last parent would not return all of its children, right?
2. No, it does not make any sense to only call setFirstResult(0) if your intention is to do pagination.
So, how can you fix this?
As I
explained in this post, collections are not very useful if they grow too large. You are better off replacing those with queries which are easier to paginate and don't suffer from the aforementioned limitation.
You can just fetch the parents firsts with one query:
Code:
List<Company> companies =
entityManager.createQuery(
"select c from Company c order by c.id", Company.class )
.setFirstResult( 40 )
.setMaxResults( 10 )
.getResultList();
You need to use the ORDER BY clause because result sets are not guaranteed to be ordered by default.
Then with the parent references, you can just issue a secondary query:
Code:
List<Department> phones = entityManager.createQuery(
"select d " +
"from Department d " +
"where d.company in :companies", Department.class )
.setParameter( "companies", companies )
.getResultList();
Then you can combine the results and send them to the UI.
But why do you really need to select entities for a paginated projection?
A
DTO projection is much more efficient and you can use the
Hibernate ResultTransformer to customize the DTO result any way you like.