有没有办法在Spring中定义默认事务管理器

Jos*_*osh 11 spring hibernate jpa transactionmanager

我有一个现有的应用程序,它将Hibernate SessionFactory用于一个数据库.我们正在添加另一个数据库来进行分析.事务永远不会交叉,所以我不需要JTA,但我确实想要将JPA EntityManager用于新数据库.

我已经设置了EntityManager和新的事务管理器,我已经认可了,但是Spring抱怨我需要对现有的@Transactional注释进行限定.我试图找到一种方法告诉Spring使用txManager作为默认值.有没有办法做到这一点?否则,我将不得不将限定符添加到所有现有的@Transactional注释中,如果可能的话我想避免这些注释.

  @Bean(name = "jpaTx")
  public PlatformTransactionManager transactionManagerJPA() throws NamingException {
    JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory());

    return txManager;
  }

  @Bean
  public PlatformTransactionManager txManager() throws Exception {
    HibernateTransactionManager txManager = new HibernateTransactionManager(sessionFactory());
    txManager.setNestedTransactionAllowed(true);

    return txManager;
  }
Run Code Online (Sandbox Code Playgroud)

我得到的错误

No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2:
Run Code Online (Sandbox Code Playgroud)

谢谢

Jos*_*osh 27

我能够使用@Primary注释来解决这个问题

  @Bean(name = "jpaTx")
  public PlatformTransactionManager transactionManagerJPA() throws NamingException {
    JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory());

    return txManager;
  }

  @Bean
  @Primary
  public PlatformTransactionManager txManager() throws Exception {
    HibernateTransactionManager txManager = new HibernateTransactionManager(sessionFactory());
    txManager.setNestedTransactionAllowed(true);

    return txManager;
  }
Run Code Online (Sandbox Code Playgroud)

  • @Mustafa是的,您只需使用属性'primary'并在您希望成为主要bean的bean上将其设置为'true'. (2认同)