Alex Rivera | Logout

Why not to use Spring's OpenEntityManagerInViewFilter

Asked 2009-10-08T14:36:46.583
39

While a lot of posts have been written on the subject of Spring's OpenSession/EntityManagerInViewFilter, I couldn't find any that mentions its flaws. From what I understand, and assuming a typical layered web application architecture using a @Transactional service layer, the filter works as follows:

  1. The filter intercepts a servlet request
  2. The filter opens an EntityManager and binds it to the current thread
  3. Web controller is called
  4. Web controller calls service
  5. Transaction interceptor begins a new transaction, retrieves the thread-bound EntityManager and binds it to the transaction
  6. Service is called, does some stuff with EntityManager, then returns
  7. Transaction interceptor flushes the EntityManager then commits the transaction
  8. Web controller prepares view, then returns
  9. View is built
  10. Filter closes the EntityManager and unbinds it from current thread

In steps 8 and 9, objects that were loaded by the thread's EntityManager are still managed. Consequently, if lazy associations are touched in these steps, they will be loaded from the database using the still open EntityManager. From what I understand, each such access will require that the database open a transaction. Spring's transaction management will be unaware of this, hence my calling it "implicit transaction".

I see 2 problems with this:

  1. Loading several lazy associations will result in multiple database transactions, a possible hit on performance
  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)

On the one hand, these 2 issues seem enough to reject using this filter (performance hit, data inconsistency). On the other hand, this solution is very convenient, avoids writing several line

Edit
Report

1 Answer

4

The main argument I've heard against OpenSessionInView and lazy loading is an excess of transactions and a negative impact on performance. It is extremely convenient to use on an app with low usage requirements, but on a high-scale app, I'd recommend using the old fashioned fully-populated DTOs (data-transfer objects).

answered 2009-10-11T03:12:48.613

Your Answer