Hibernate 延迟加载类属性

Java web程序员偶尔会遇见此类问题:

 

could not initialize proxy - the owning Session was closed

1.

 

This error means that you're trying to access a lazily-loaded property or collection, but the hibernate session is closed. Lazy loading in Hibernate means that the object will not be populated (via a database query) until the property/collection is accessed in code. Hibernate accomplishes this by creating a dynamic proxy object that will hit the database only when you first use the object. In order for this to work, your object must be attached to an open Hibernate session throughout it's lifecycle. Check to see how you're managing your session. You may need to reattach objects to a new session if the session is being closed in some other place.

 

2.

 

    

attach

 

Purpose

Attaches a detached domain instance to the Hibernate session bound to the current thread

 

Examples

 

def b = Book.get(1)
b.title = "Blah"
b.save(flush:true)

b.discard()

if(!b.isAttached()) { b.attach() }

 

Description

Grails uses Hibernate which manages each persistent object in a persistence session. A new session is created per request and is closed at the end of the request. If an object is read from the session and placed into a web scope such as the HttpSession it is seen as detached, since the persistence session has been closed. You can use the attach() method to re-attach an existing persistent instance to the persistence session of the current request.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值