Anand
Anand

Reputation: 21320

Lazy loading working in non-transactional class/method in Hibernate

I am working in Spring-Hibernate application. Flow is as usual: Controller --> Service --> DAO.

I have annotated Service layer class with @Transactional, thereby marking every method transactional in that class.In service class, I made a DAO call to get some domain object and then converting it into DTO/VO object which will be passed to controller.For converting domain object to DTO, I have written another custom static class(class having only static methods) like ObjectMapper which will do this conversion.

Now, domain object has some child object(One to Many) which is lazily loaded. So, when in ObjectMapper, i access that child getter method, an extra database call is issued, which is working fine. What I don't understand is that since ObjectMapper is not transactional, I was expecting some exception to be thrown like Session is closed while making database call to fetch child object from database.I am using getCurrentSession of Session Factory in DAO.

Can someone please explain me this behavior?

Upvotes: 0

Views: 626

Answers (2)

Raphael Roth
Raphael Roth

Reputation: 27373

I suppose you either call your ObjectMapper from the transactional Service method (you should) or if not, maybe you are enabled "hibernate.enable_lazy_load_no_trans" which keeps the hibernate session open

Upvotes: 1

dunni
dunni

Reputation: 44545

As long as the call to the static class/method, which transforms your objects, is made in the transactional method of the DAO, the session is still open and will be used for the database calls.

Upvotes: 0

Related Questions