Why not to use Spring’s OpenEntityManagerInViewFilter

As you said, the OpenSessionInView filter is very convenient in web applications. Regarding the limitations you mentioned:

1) Loading several lazy associations will result in multiple database transactions, a possible hit on performance.

Yes, going to the DB often might lead to performance problems. Ideally you want to fetch all the data you need in one trip. Consider using Hibernate join-fetch for this. But fetching too much data from the DB will also be slow. The rule of thumb I use is to use join fetching if the data is needed every time I paint the view; if the data is not needed in most cases, I let Hibernate lazy fetch it when I need it – the threadlocal open session helps then.

2) The root object and its lazy associations are loaded in different database transactions, so the data may possibly be stale (e.g. root loaded by thread 1, root associations updated by thread 2, root associations loaded by thread 1).

Imagine writing this application in JDBC – if the application’s consistency requirements demand that the root and leaves both should be loaded in the same txn, use join fetching. If not, which is often the case, lazy fetching won’t lead to any consistency problems.

IMHO, the more important disadvantage with OpenSessionInView is when you want your service layer to be reused in a non-web context. From your description, you don’t seem to have that problem.

Leave a Comment