Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to define a default transaction manager in Spring

I have an existing application that uses the Hibernate SessionFactory for one database. We are adding another database for doing analytics. The transactions will never cross so I don't need JTA, but I do want to use JPA EntityManager for the new database.

I've set up the EntityManager and the new transaction manager, which I've qualified, but Spring complains that I need to qualify my existing @Transactional annotations. I'm trying to find a way to tell Spring to use the txManager one as the default. Is there any way of doing this? Otherwise I'll have to add the qualifier to all the existing @Transactional annotations which I would like to avoid if possible.

  @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;
  }

Error I'm getting

No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2:

Thanks

like image 917
Josh Avatar asked Apr 10 '13 21:04

Josh


1 Answers

I was able to solve this using the @Primary annotation

  @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;
  }
like image 136
Josh Avatar answered Sep 18 '22 23:09

Josh