Hibernate无法初始化代理 - 没有会话 [英] Hibernate could not initialize proxy - no Session

查看:204
本文介绍了Hibernate无法初始化代理 - 没有会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码检索与用户相关的所有信息:

  SessionFactory sessionFactory = HibernateUtilities.configureSessionFactory(); 
Session session = sessionFactory.openSession();
UserDetails ud = null;
Set< Address> userAddress = null;

尝试{
session.beginTransaction();
ud =(UserDetails)session.get(UserDetails.class,1);
userAddress = ud.getAddresses();
session.getTransaction()。commit();
} catch(HibernateException e){
e.printStackTrace();
session.getTransaction()。rollback();
} finally {
session.close();
}

System.out.println(ud.getName()); (Address addr:userAddress){
System.out.println(State+ addr.getState());



ud.getAddresses()简单地返回一组地址 es的用户。



我的问题是:为什么<即使会话已经关闭,code> ud 对象仍然有其值(例如,名称)? getAddresses() UserDetails 类的实例变量。但为什么我不能检索它的值,但我可以检索 UserDetails 类的常规实例变量? code> ud.getAddresses()是 @EmbeddedCollection

解决方案

  userAddress = ud.getAddresses(); 
session.getTransaction()。commit();
(Address addr:userAddress){

hibernate文档与懒惰协会合作明确地呼吁作为错误的访问类型。只有在会话仍处于打开状态时,才能与懒惰相关的对象进行交互。这部分文档还提供了替代方法来访问这种懒惰的对象成员,我们更愿意在我们的应用程序中使用标准中指定获取模式为JOIN。


My code retrieves all information related to the user:

SessionFactory sessionFactory = HibernateUtilities.configureSessionFactory();
Session session = sessionFactory.openSession();
UserDetails ud = null;
Set<Address> userAddress = null;

try {
    session.beginTransaction();
    ud = (UserDetails) session.get(UserDetails.class, 1);
    userAddress = ud.getAddresses();
    session.getTransaction().commit();
} catch (HibernateException e) {
    e.printStackTrace();
    session.getTransaction().rollback();
} finally {
    session.close();
}

System.out.println(ud.getName());

for(Address addr: userAddress){
    System.out.println("State " + addr.getState());
}

The ud.getAddresses() simply returns a set of Addresses of the user.

My question is: why does the ud object still have its value (eg, name) even though the session is already closed? getAddresses() is an instance variable of the UserDetails class. But why can't I retrieve its value but I can retrieve regular instance variables of the UserDetails class?

ud.getAddresses() is an @EmbeddedCollection.

解决方案

userAddress = ud.getAddresses();
session.getTransaction().commit();
for(Address addr: userAddress) {

The hibernate documentation for working with lazy associations clearly calls out this kind of access as an error. You can interact with lazily associated objects only while the session is still open. That portion of the documentation also provides alternatives to access such lazily associated members of an object and we prefer to specify the fetch mode as JOIN in the criteria used, in our applications.

这篇关于Hibernate无法初始化代理 - 没有会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆