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;
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;
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;
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.
java hibernate lazy-loading
Jens fischer
source share