Spring JPA : Application managed persistence context with @Transactional and @PersistenceContext

。_饼干妹妹 提交于 2019-12-05 07:06:26

Spring's handling of the @PersistenceContext annotation does almost exactly what you're after, with one big difference: you always get a transaction scoped EntityManager and Spring injects always the same instance for the same thread, so you have kind of propagation and don't have to worry about thread-safety. But you'll never get an extended context this way!
Believe me, Spring 3 and extended persistence context don't play well together, maybe this will change in Spring 3.1 but I'm afraid that's not in their focus. If you want to use an extended persistence context let Spring inject the EntityManagerFactory (via @PersistenceUnit annotation) and then create the EntityManager on your own. For propagation you'll have to either pass the instance as a parameter or store it in a ThreadLocal yourself.

Indeed to have a application managed persistence context, you need to somehow "hack" the @Transactional & @PersistenceContext infrastructure by providing them your own Entity Manager and do not let Spring create its own.

The key to achieve this is to play a little bit with the TransactionSynchronizationManager class to register your own Entity Manager to the thread local, Spring will use it to inject to the @PersistenceContext attribute.

I had this need some time ago for my own application and I've designed a small architecture based on Spring AOP to manage the extended persistence context.

Details here: JPA/Hibernate Global Conversation with Spring AOP

When you configure your transactions via @Transactional, then you should handover the configuration of your transactions to the annotation.
Here you start your transaction and then hope that the @Transactional will also be triggerd.
for more information you would best start reading http://static.springsource.org/spring/docs/2.5.x/reference/transaction.html => 9.5.6. Using @Transactional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!