我有一个具有以下结构的方法:
public void run(){ ... for (...) { //this part works correct User.withTransaction { User user = User.findByUsername(...); Position pos = Position.findByName(...) if(pos){ ... } else { ... try{ pos.save(flush:true); user.position = pos; } catch (Exception e){ ... } } ... try{ user.save(flush:true, failOnError: true); } catch (Exception e){ ... } } } //this part doesn't work User.findAll().each { ... if (...){ User.withTransaction{ ... //here the operation fails with //org.hibernate.LazyInitializationException: //could not initialize proxy - no Session if (!userDetailsMap.containsKey(it.username) && it.userStatus != blocked){ it.userStatus = blocked it.save(flush:true) } } } } }
我在这里遇到的异常是org.hibernate.LazyInitializationException: could not initialize proxy - no Session代码的第二部分。在此,该userStatus字段是对其他域类的引用。
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
userStatus
我尝试在属性检查之前添加it.refresh()和添加Hibernate.initialize(it)到代码中,但是没有用。我在这里做错了什么?
it.refresh()
Hibernate.initialize(it)
upd:我尝试it.attach在检查属性之前调用方法,但是在方法调用之后立即调用it.attachedis 的值false。
it.attach
it.attached
false
我不认为您在做任何“错误”的事情,只是对象从hibernate会话中脱离了。我会尝试的几件事: