If we want the publisher object can be accessed outside the session, there will be two possible
solutions. One is to initialize the publisher explicitly, we can call the method Hibernate.initialize()
for this task. This will force the publisher object to be loaded from database.
Session session = factory.openSession();
try {
Book book = (Book) session.get(Book.class, id);
Hibernate.initialize(book.getPublisher());
return book;
} finally {
session.close();
}
Another solution is to turn off the lazy initialization feature for this association. This may decrease
the performance as the publisher object will be loaded together with the book object every time.
<hibernate-mapping package="mo.org.cpttm.bookshop">
<class name="Book" table="BOOK">
...
<many-to-one name="publisher" class="Publisher" column="PUBLISHER_ID"
lazy="false" />
</class>
</hibernate-mapping>