【发布时间】:2015-07-29 20:18:14
【问题描述】:
我对以下实体有疑问:森林、树木、树叶。正如你可以想象的那样,一片森林可以有很多树,而一棵树有很多叶子。
我想延迟加载森林中的所有树木并急切地加载树木的所有叶子。我的带有休眠注释的代码如下所示:
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() 方法会导致一组 select 语句。 Hibernate 执行一条语句来获取所有树,并为每棵树执行第二条语句以收集所有叶子。 在我看来,hibernate 应该只生成一个语句,使用连接来同时收集树木和树叶。
谁能告诉我问题的原因以及如何解决? 非常感谢!
顺便说一句:如果我将森林树的获取策略更改为 EAGER,则一切正常,只需一条语句。
【问题讨论】:
标签: java hibernate lazy-loading