Recently I’ve been learning a lot about the subtle nuances of the EE/CDI persistence world and in this post I wanted to give an overview of what I’m finding.
@PersistenceContext(type = PersistenceContextType.EXTENDED)
Extended persistence context – the idea sounds great! Let the container manage a persistence context which can span multiple requests. Surely this would eliminate many LazyInitializationExceptions and make stateful interactions with the server a breeze…
Sadly persistence in an EE application is often complex, hard to understand and when you get exceptions they may not even tell you exactly what the underlying real cause is. In one of my latest applications I’m trialing doing away with the extended persistence context entirely.
The Dark Side of Extended Persistence Contexts
Having developed numerous Seam2 apps I was used to creating loosely coupled components and injecting an EntityManager in where ever I needed one. Doing that with CDI/EE quickly lead to this: “Found extended persistence context in SFSB invocation call stack but that cannot be used” – this seemed odd as I was only accessing my data using an extended persistence context and my understanding was that this would be propagated to other SFSB as required. After a little ‘Googling’ I found this post: http://kennethflynn.wordpress.com/2012/07/04/jbas011437-extended-persistence-contexts-and-incorrect-error-messages/ It seems that its possible to get multiple extended persistence contexts and they are incompatible with each other!
- Only available in Stateful EJBs
- Problems mixing extended with non-extended contexts
Deltaspike – A possible solution?
Seam3 and later Deltaspike offered their own persistence modules which claim to help the developer overcome these complexities. Seam3 was abandoned by RedHat and much of the code ended up under the Deltaspike umbrella. Deltaspike looks like a promising solution and has some nice features. The main reason I’m not going with it at this time is its lack of being “mainstream” and when I started writing this post it didn’t feel very mature as version 1.0 was not out – this has since come out in June 2014. This might seem silly and I may catch flack for it and even live to regret this decision but at this point in time that’s where I stand. There just doesn’t seem to be the uptake of use and massive backing for this project at the moment although I could be wrong. The project still seems to be under active development with git commits just a few days ago and I would hope that in time much of the modules from Deltaspike can be merged back into the main CDI/EE spec.
So this really only left me with doing some research and writing something myself that suited my needs. I intend to cover the specifics of my current solution in more detail in a separate post but if you want to just jump straight into the code you can find it here: https://github.com/cbensemann/SimplePersistence.