我有以下实体的问题:森林,树,叶.你可以想象森林可以有很多树木,树上有很多树叶.
我想懒得加载森林的所有树木,并渴望加载一棵树的所有树叶.我的hibernate注释代码如下所示:
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
我的问题:加载一个林并调用getTrees()方法会产生一组选择语句. Hibernate执行一个语句来获取所有树,并为每个树执行第二个语句以收集所有叶子.
在我看来,hibernate应该只生成一个语句,使用连接,同时收集树和叶子.
有人可以告诉我,我的问题的原因以及我如何解决它?
非常感谢!
再见:如果我将森林树的提取策略更改为EAGER,一切正常,只有一个语句.