hibernate laze

经常会莫名奇妙的抛出异常

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,我觉得还挺确切。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值