这是我的休眠 POJO 类。
@Entity
@Table(name = "PARENT")
public class Parent {
@Id
private int id;
@Column(name = "NAME")
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
private List<Child> children;
// Getters and Setters...
}
@Entity
@Table(name = "CHILD")
public class Child {
@Id
private int id;
@Column(name = "NAME")
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PARENT_ID", nullable = false)
private Parent parent;
// Getters and Setters...
}
从我对休眠的了解中,有两种方法。(我还是菜鸟:P)
Session session = sessionFactory.openSession();
List<Child> children = null;
try {
children = session.createCriteria(Child.class, "C")
.add(Restrictions.eq("C.parent", parent)
.list();
} finally {
session.close();
}
或者
Session session = sessionFactory.openSession();
List<Child> children = null;
try {
session.refresh(parent);
children = parent.getChildren();
} finally {
session.close();
}
后一个使用刷新的,我在尝试 Hibernate 时意外发现。
Q.1 最好的方法是什么?
Q.2 为什么要使用 Criteria API 或 HQL 来获取延迟加载成员,而您只需调用 getter 方法即可获取所有子项?