我最近将一个使用本地Hibernate实体和会话管理的项目转移到了Spring,使用注释驱动的依赖注入和事务管理。
我的实体结构如下:
@Entity
@Table(name = "PARENT",uniqueConstraints=@UniqueConstraint(columnNames={"parentName"}))
public class Parent implements Serializable, {
static final long serialVersionUID = 1L;
@Id
private int id;
@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Child> child = new HashSet<Child>();
}
@Entity
@Table(name = "CHILD", uniqueConstraints = @UniqueConstraint(columnNames = {
"childName", "parent_id" }))
@SequenceGenerator(name = "CHILD_SEQ", allocationSize = 1, sequenceName = "CHILD_SEQ")
public class Child implements Serializable {
static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CHILD_SEQ")
private int id;
private String childName = ""; //$NON-NLS-1$
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
}
Here's what happens.
I get all the parent objects which contain individual lists of child objects. This works quickly, I have the full object tree in memory in my debugger I can see every Child object is loaded correctly.
public List<Parent> getParents() { return em.createQuery("from Parent",Parent.class).getResultList(); }
I then try and get every Child object and the application freezes my PC slows down and after a few hours I get the Out on memory exception.
public List<Child> getChildren() { return em.createQuery("from Child",Child.class).getResultList(); }
我无法理解的是为什么查询父级如此迅速并给我每个对象,但子查询却会中断。