0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But then there is a coupling between controller and dao?
No, by implementing OpenSessionInViewFilter you are actually removing session management from your code thus separating your concerns which is good. Its a servlet filter which will manage hibernate session for you and you can write code without being worried about the hibernate session.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.