Search code examples
javaoracle-databasehibernatehibernate-mappinghibernate-criteria

Retrieve Hibernate associated entity with pagination


I am stuck with an issue. I have 3 tables that are associated with a table in one to many relationship.

  • An employee may have one or more degrees.
  • An employee may have one or more departments in past
  • An employee may have one or more Jobs

I am trying to fetch results using named query in a way that I fetch all the results from Degree table and Department table, but only 5 results from Jobs table. Because I want to apply pagination on Jobs table.

But, all these entities are in User tables as a set. Secondly, I don't want to change mapping file because of other usages of same files and due to some architectural restrictions.

Else in case of mapping I could use BatchSize annotation in mapping file, which I am not willing to do.


Solution

  • The best approach is to write three queries:

    1. userRepository.getDegrees(userId);
    2. userRepository.getDepartments(userId);
    3. userRepository.getJobs(userId, pageIndex);

    Spring Data is very useful for pagination, as well as simplifying your data access code.

    Hibernate cannot fetch multiple Lists in a single query, and even for Sets, you don't want to run a Cartesian Product. So use queries instead of a single JPQL query.