Reputation: 483
I'm using spring-mvc and hibernate session-factory.
@Controller
|
-> @Service (@Transactional)
|
-> @Repository
I have 2 entities, User
and Address
.
User has a List<Address>
with FetchType=LAZY
.
If I add an Address
object via user, within a @Controller
, I get failed to lazily initialize a collection of role - could not initialize proxy - no Session
exception.
But If I do this inside the service layer which is wrapped with @Transactional
, operation works nicely.
I found out about hibernate proxies,...etc.
My question is, why @Controller
cannot change an entity object which is retried from @Service
layer. Because @Controller
has no idea whether it is a hibernate proxy or anything else. To the @Controller
it is just an object. So why I'm getting an error, if I change an entity object inside the @Controller. This is only happening to entity properties which are marked as FetchType=LAZY
.
Upvotes: 0
Views: 1809
Reputation: 715
When you choose a property to be lazily loaded, hibernate wraps those around a proxy having the session object in which the parent was fetched.
If you try to access the property after the session scope you will get this error.
Looks like your session is getting created and closed in service layer.
Implement OpenSessionInView Filter provided by spring, it will close the session after response being send.
Upvotes: 2