Spring and PersistenceContextType.EXTENDED

June 30, 2011

Recently I was introduced to a project that’s already 4 months in development. After a day of coding I realized there’s something wrong with the session and transaction management. Then I found something that I’ve never used and didn’t quite know when it should be used – the EntityManager was injected into DAO objects via @PersistenceContext(type=PersistenceContextType.EXTENDED)

First thing to do – google. Found this spring forum discussion, which made it clearer, but not quite.

Then I started debugging and realized that the application is de-facto using the session-per-application anti-pattern. Not only that, but each DAO got its own entity manager (and underlying session) instance.

An important note here – I say “entity manager and underlying session”, because Hibernate simply wraps its Session with an implementation of the standard EntityManager interface. So it makes a little difference whether we talk about entity manager or session.

What happens? PerssitenceContextType.EXTENDED means that you, rather than spring, are in charge of managing your session. All spring does is create it on startup and close it on shutdown. The other option (which is the default – PerssitenceContextType.TRANSACTION) lets spring’s transaction managers create the entity manager (and session) for each request, start a transaction, and when you are finished – commit the transaction and close the session.

This is called session and transaction management, and it is one of the most important things to do in a spring & JPA project. It should be done right almost from the start, so the next time you do such a project, spend extra days to get this right.

But what is wrong with the above situation? Here are some effects of the extended manager:

  • Each DAO gets a different instance of the EntityManager so you can’t do any meaningful work that involves two DAOs. If you insert a records with one EntityManager and try to use it in another one – it won’t work. The first hasn’t been flushed, and the second does not have the 1st level cache.
  • If a session does not get closed it accumulates entities (it stores them in memory so that it doesn’t have to fetch them multiple times from the DB). Which is a pure memory leak.
  • It is not thread-safe. The Session and EntityManager objects are not thread-safe. Since you are most likely to inject them in a singleton DAO object you will start getting weird results due to concurrent access

How did this happen and why it got unnoticed for so long? I have a theory. 1. People started using the DAO layer directly from the web layer 2. Something wasn’t working for someone, so he changed the type of the persistence context, which made his code work. 3. As the project is not having many inserts, people were mainly reading data and didn’t stumble upon the various problems. 4. There hasn’t been extensive testing, with multiple people on the same instance, so the concurrency problems were not spotted.

One more thing – PersistenceContextType.EXTENDED is useful in limited scenarios. The so called long-running session or session-per-conversation. When you have wizards you can have multiple requests with the same session, which saves some detaching and merging. But should you use that, make sure you don’t do it for the whole application and that you are absolutely know what you are doing. And close the session when the conversation ends. Another scenario is usage in EJB stateful beans. (In general, the extended persistence context makes more sense in a JavaEE environment)

So to summarize:

  • Spend a lot of time to properly configure session and transaction management and try to get it right
  • Almost never use PersistenceContextType.EXTENDED in spring (outside a JavaEE container at least)
  • Don’t use the DAO layer directly from the web layer. A base service class with wrappers for the most used operations would not be too verbose, but will save you countless headaches
  • Code reviews should be thorough, or commit rights to core classes and configurations should be limited to a number of people that know what they are doing
If you find the content interesting, you can subscribe and get updates


 

9 Responses to “Spring and PersistenceContextType.EXTENDED”

  1. In seam framework using extended persistence context is a good thing, you should use it within a seam conversation, its like a session but has a begin and end. end removes all the data from the “conversation” session.

    In that time you use the conversation you have a hibernate extended persistence context, which is a very good thing because you don’t have to do a hibernate merge later! the entities don’t become detached ever. They are always attached to the persistence context.

  2. Yeah, I mentioned that conversations are a proper case to use extended context. You can have that with spring as well. (Webflow, plus an incoming feature in 3.1

  3. Hi,
    Nice article. As far as i remember it was recommended to use EXTENDED only in the case you are using Stateful beans where it supports passiviation and activation. Thx for shedding the light on the subject matter.

    I trust this lends it self as a good case study to remember to study what each attribute does rather than blindly using them.

    God Bless

    Dinuka

  4. In any case, assume you do need an extended persistence context. How would you go about closing that entity manager in a Spring-managed environment?

    Lots of people are asking this question on the spring forum, but do not seem to get an answer…

  5. It depends how are you using it. The way to close it is always manually.

  6. There’s something worth of attention: When using PersistenceContextType.TRANSACTION, then the POJOs fetched via queries outside transactions are detached as soon as they are returned. This means that if subsequent code touches a POJO field that would require lazy loading, an exception would occurr.

  7. I do not agree with your assertion “Almost never use PersistenceContextType.EXTENDED in spring (outside a JavaEE container at least) ”

    Below is a code snippet of Hibernate 3.5 GA:

    org.hibernate.ejb.EntityManagerFactoryImpl

    public EntityManager createEntityManager(Map map) {
    //TODO support discardOnClose, persistencecontexttype?, interceptor,
    return new EntityManagerImpl(
    this, PersistenceContextType.EXTENDED, transactionType,
    discardOnClose, sessionInterceptorClass, map
    );
    }

    Indeed, de facto when using @PersistenceContext to inject an EntityManager into your bean, Spring will delegate to the Hibernate EntityManagerFactory the task of creation of new instances of EntityManager.

    As the source code shows, the persistence context type is currently ALWAYS set to EXTENDED ….

    Furthermore, according to EJB3 specs (JSR 220, chapter 3.3.1), with an EXTENDED persistence context, the entities are NOT detached at the end of a JDBC transaction whereas with TRANSACTION persistence context, they are.

  8. I didn’t see how that is an argument against my claim?

    Yes, when you manually create the entity manager, it has to be EXTENDED – that means you manage it. But in case you use spring declarative transaction and session management, having it EXTENDED means spring won’t do what you expect it to. And you’ll have memory leaks and unexpected behaviour.

  9. this was very helpful to me.My persistenceType was originally set to EXTENDED and I was getting an error but when i changed it to TRANSACTION, everything is well now. Thanks a lot.

Leave a Reply