Hibernate OneToMany pagination

how can I map a one-to-many relationship in Hibernate where a multi-page page should be paginated? (i.e. you have hundreds or more related objects)
Using the OneToMany annotation (or its equivalent xml) is impractical, since loading a one-way object extracts with it all the objects associated with it, causing a memory crash (even if you use lazy loading) .
A possible approach (which I already use) is to add the getter method to the DAO implementation, where you can enter pagination options. However, I see that this is not ideal, because you lose some functions, such as cascading (for example, I have to include setter methods in the DAO class to bind objects). In addition, you lose the meaning of OOP because a one-way object does not have a method for retrieving the associated multilateral objects. What is the best solution?
To illustrate my point, let's say I have two classes with the following relationship between them: A has-many B.
I cannot write the A.getAllB () method using the OneToMany annotation, since there are hundreds of Bs related to A. So, to break the results, I create a separate ADaoImpl class with the getAllB () method, where I can enable pagination params, to return only one page of data at a time. It's right? Any help would be appreciated.

+5
source share
1 answer

I think I would do the same thing that you suggest: Create a new method on my dao that accepts pagination options and returns the specified result page. Regardless of whether you want to keep the children in the parent object, it is up to you. You can create a transition field for these objects.

  public class Parent {
    @Transient
    private List<Child> children;

  }

  public class ParentDao {

    // Solution 1 - You can keep the parent/child association
    public void loadChildren(Parent parent, int firstResult, int maxResults) {
       // do your query
       parent.setChildren(query.list());
    }

    // Solution 2 - Or just have your dao directly return the children and remove the list from Parent
    public List<Children> getChildren(Parent parent, int firstResult, int maxResults) {
      // do your query
      return query.list();
    }
  }

, OO . . "OO".

+2

All Articles