简体   繁体   中英

Loading many-to-one class - Hibernate

I would like to load a House object from database like this:

House temp = DataBaseConnector.getInstance().findHouseByID(id);
System.out.println(temp.getType().getName());

but anytime I try to access getType() field I get error:

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) ..

findHouseById function looks like this:

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 .

Here some information about object states:

https://docs.jboss.org/hibernate/core/3.3/reference/en/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.

Either you change the fetch strategy of field type to EAGER so no database access is needed at this point, take a look here:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM