Thursday, April 8, 2010

Lazy loading under a Spring OpenSessionInViewFilter without a Transaction

You can't do it.

Yeah I know it's a pretty dry and boring topic, but this needs to be said.

If you are using an OpenSessionInViewFilter*, then you must use transactions for all data access, even just for readonly access.

They don't make it super clear in the javadoc, but OpenSessionInViewFilter REQUIRES, DEMANDS and EXPECTS all data access to be wrapped in a transaction. If you are getting LazyLoadExceptions and don't know why, then make sure your data access is transactional.

Of course, the transaction can be finished before you try to do the lazy loading; OpenSessionInViewFilter just expects that a transaction happened at some prior point in the request.


* and expect to be able to lazily load your data, which is pretty much the point of OSIV

1 comment:

Anonymous said...

Thanks a bunch!

I had been wondering what was going wrong, since I saw Spring's OSIV filter opening sessions just fine, but hibernate would not use them.