JPA Multiple Transaction Managers

前端 未结 2 1468
庸人自扰
庸人自扰 2020-12-16 00:59

I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured

2条回答
  •  半阙折子戏
    2020-12-16 01:49

    I guess you have 2 choices

    If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple TransactionProxyFactoryBean to define transaction boundaries, eg:

    
    
        
        
        
            
               PROPAGATION_REQUIRED
               PROPAGATION_REQUIRED
               PROPAGATION_REQUIRED,readOnly
            
        
    
    
    

    If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The API states:

    This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.

    What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:

    
    
    
        
    
    

    If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet)

    As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using?

    The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.

    Hope this helps

提交回复
热议问题