How to configure transaction management for working with 2 different db in Spring?

前端 未结 4 770
无人共我
无人共我 2020-12-02 10:49

I have 2 databases (MySql and HSQLDB). I configured 2 data sources and 2 EntityManagerFactory beans. I can also configure 2 correspondent JpaTransactionManager beans.

4条回答
  •  抹茶落季
    2020-12-02 11:02

    Since its after a longtime since the correct answers.

    Skaffman may be correct in terms of usability of JpaTransactionManager for multiple databases.

    But there is working solution for using 2 different databases with 2 different JpaTransactionManager.

      @Bean(name = "db2TransactionManager")
      public PlatformTransactionManager transactionManager2() throws NamingException {
        JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory());
        return txManager;
      }
    
      @Bean
      @Primary
      public PlatformTransactionManager transactionManager() throws Exception {
         JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory());
        txManager.setNestedTransactionAllowed(true);
        return txManager;
      }
    

    @Primary should be used to specify for the ones where you don't specify qualifier name in @Transactional

提交回复
热议问题