经常会莫名奇妙的抛出异常
org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
看了很多资料都不是很明白,偶然间看到hibernate的doc,
http://www.hibernate.org/hib_docs/v3/reference/en/html/performance.html
有下边这个列子
s = sessions.openSession();
Transaction tx = s.beginTransaction();
User u = (User) s.createQuery("from User u where u.name=:userName")
.setString("userName", userName).uniqueResult();
Map permissions = u.getPermissions();
tx.commit();
s.close();
Integer accessLevel = (Integer) permissions.get("accounts"); // Error!
解释为
Since the permissions collection was not initialized when the Session was closed, the collection will not be able to load its state. Hibernate does not support lazy initialization for detached objects . The fix is to move the code that reads from the collection to just before the transaction is committed.
突然理解了。呵呵。
是延迟初始化错误。由于对一个类或者集合配置了延迟检索策略,那么必须当代理类实例或代理集合处于持久化状态(即处于Session范围内)时,才能初始化它。如果在游离状态时才初始化它,就会产生延迟初始化错误。
把many-to-one 加上lazy="false"
在一篇文章上看到说lazy可以理解为ignore,我觉得还挺确切。