【发布时间】:2014-08-27 07:28:09
【问题描述】:
A 有两个休眠实体和一个简单的 1:N 集合关系:
@Entity
public class Root {
@OneToMany(mappedBy = "root", fetch = FetchType.LAZY)
public Set<Position> getPositions() {
return positions;
}
}
Spring MVC web 应用程序加载根实体并初始化惰性集合:
@Transactional
public Root findFullById(Long id) {
Root root = (Root) getSession().get(Root.class, id);
Hibernate.initialize(root.getPositions()); // this line fails
return root;
}
在此方法之前有NO个数据库操作。
这适用于我的 Oracle 11 DB 中的几乎所有实体,但有些(似乎是随机的)因“org.hibernate.HibernateException:集合不与任何会话相关联”而失败。据我了解,这是因为 PersistentSet 中的会话已关闭,但为什么它首先关闭?
最奇怪的是,如果我在这一行设置断点并在调试器中(即在 eclipse Inspect 窗口中)调用 Hibernate.initialize(),它会成功加载集合。
什么可以关闭会话?有什么好的地方可以调试这个(即休眠中某处的断点)?
更新:
我在 Position 类中有另一个关系:
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "POSITION_NUMBER", referencedColumnName = "POSITION_NUMBER", insertable = false, updatable = false)
public Set<Child> getChildren() {
return children;
}
失败的行为空,但将其更改为 @Transient 可以解决问题。
【问题讨论】:
-
你是如何处理 Hibernate 会话打开和关闭的?
-
使用 tx:annotation-driven 和 org.springframework.orm.hibernate3.HibernateTransactionManager
-
在 OpenSessionInView 过滤器中获得战利品