Lazy loading of children who have interesting collections inside

I have a problem with the following objects: Forest, Tree, Leaf. As you can imagine, there can be many trees in a forest, and a tree has many leaves.

I would like to be lazy to load all the trees in the forest and willingly load all the leaves of the tree. My code with hibernation annotations is as follows:

Forest.java

@Entity @Table(name = "Forests") public class Forest implements Comparable<Forest> { @Id @Column(name = "forestnumber", length=10, nullable=false) private String number; @OneToMany(fetch=FetchType.LAZY, mappedBy="forest") private Set<Tree> trees = null; // some other attributes and methods 

Tree.java

  @Entity @Table(name = "Trees") public class Tree implements Comparable<Tree> { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="tree_id", nullable=false) private int id; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "forestnumber", nullable = false) @Fetch(FetchMode.JOIN) private Forest forest; @OneToMany(fetch=FetchType.EAGER, mappedBy="tree") @Fetch(FetchMode.JOIN) private Set<Leaf> leafs = null; // some other attributes and methods 

Leaf.java

  @Entity @Table(name = "Leafs") public class Leaf implements Comparable<Leaf> { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="leaf_id", nullable=false) private int id; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "tree_id", nullable = false) @Fetch(FetchMode.JOIN) private Tree tree; // some other attributes and methods 

My problem: loading the forest and calling the getTrees () method results in a set of selected expressions. Hibernate performs one statement to get all the trees, and the second for each tree to collect all the leaves. In my opinion, hibernate should only generate one statement, using a join, to collect trees and leaves at a time.

Can someone tell me the cause of my problem and how can I fix it? Many thanks!

For now: If I change the forest tree selection strategy to EAGER, everything will be fine, with only one statement.

+7
java hibernate lazy-loading
source share
2 answers

You can try to initialize

 Hibernate.initialize(forestInstance); 

Or write a request with a connection that provides fetch to get all the children looking forward to.

see also

Is there a way to change the JPA fetch type for a method?

0
source share

Remove fetch = FetchType.EAGER. Unwanted fetch runs cascading select commands.

0
source share

All Articles