Hello,
I am not a beginner in hibernate, but I am a beginner in working with Hibernate in Spring. I read the book Spring in Action. So I wrote a small application to comprehend the examples in the book. Here an extraction of my application. I can give you more, if you want.
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public void runQuery()
{
final BuildingDAO buildingDAO = ( BuildingDAO ) applContext.getBean( "buildingDAO" );
final Building building = buildingDAO.getBuildingById( "HQ" );
logger.debug( "Loaded building: " + building.getId() );
logger.debug( "Loaded building: " + building.getName() );
}
The object is loaded without any problems. The log of the Primary-Key is no problem, too. But the log of the string attribute causes a LazyInitializationException. I understand why this happens. Hibernate returned a proxy with proxied atributes. When I want to access to a lazy-loaded attribute, Hibernate tried to load the value but the session is closed. Lazy loading is a great feature of Hibernate and I don't want to miss it.
Spring manages the session-handling for me. Spring opens a Hibernate session in the load-method of the Hibernate-template and closes the session after the method has finished.
But now I want to advise Spring that the session should be open in the whole method (runQuery()), which is shown above. I want to display some attributes of the object. I mentioned I can use a tranaction-manager of Spring to do that. So I use the Transactional-Annotation of Spring. But it doesn't work. Maybe my assumption to use the transaction-manager is wrong.
Has anybody an idea to advise Spring to hold open a session for the whole method?