[英]Loading many-to-one class - Hibernate
I would like to load a House
object from database like this: 我想从数据库中加载
House
对象,如下所示:
House temp = DataBaseConnector.getInstance().findHouseByID(id);
System.out.println(temp.getType().getName());
but anytime I try to access getType()
field I get error: 但是任何时候我尝试访问
getType()
字段都会出现错误:
Exception in thread "AWT-EventQueue-0" org.hibernate.LazyInitializationException: could not initialize proxy - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185) at mapping.Type_$$_jvstd13_0.getName(Type_$$_jvstd13_0.java) ..
线程“ AWT-EventQueue-0”中的异常org.hibernate.LazyInitializationException:无法初始化代理-org.hibernate.proxy.AbstractLazyInitializer.getImplementationation上的org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)上没有会话(org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)处的AbstractLazyInitializer.java:286),位于mapping.Type _ $$ _ jvstd13_0.getName(Type _ $$$ _ jvstd13_0.java)处。
findHouseById
function looks like this: findHouseById
函数如下所示:
public static House findHouseByID(Integer id) {
Session session = getSessionFactory().openSession();
House e = (House) session.load(House.class, id);
session.close();
return e;
}
Any help would be appreciated :) 任何帮助,将不胜感激 :)
As the exception says, you have no (hibernate) session at the point you are calling temp.getType()
because you closed the session after loading your object within the method findHouseByID
. 如异常所示,您在调用
temp.getType()
没有会话(休眠),因为在将对象加载到findHouseByID
方法中后关闭了会话。
Here some information about object states: 这里有一些关于对象状态的信息:
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html https://docs.jboss.org/hibernate/core/3.3/reference/zh/html/objectstate.html
Due to this fact you will get a LazyInitializationException
because hibernate tries to access the database to propagate the not initialized field type
on the detached object. 由于这个事实,您将获得
LazyInitializationException
因为休眠试图访问数据库以在分离对象上传播未初始化的字段type
。
Either you change the fetch strategy of field type
to EAGER
so no database access is needed at this point, take a look here: 您可以将字段
type
的获取策略更改为EAGER
因此此时不需要数据库访问,请在此处查看:
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/FetchType.html https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/FetchType.html
Or you have to increase the scope of your session (call getType
before your session is closed). 或者,您必须增加会话的范围(在关闭会话之前调用
getType
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.