spring – 多个事务管理器注释配置

我在基于注释的配置类中配置了两个事务管理器:

@Configuration
@EnableTransactionManagement
public class DBConfig implements TransactionManagementConfigurer {

//...

@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
    return defTransactionManager();
}

@Bean
@Qualifier("defSessionFactory")
public LocalSessionFactoryBean defSessionFactory() {
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
    sfb.setDataSource(defDataSource());

    Properties props = new Properties();
    //...

    sfb.setHibernateProperties(props);
    sfb.setPackagesToScan("my.package");

    return sfb;
}

@Bean
@Qualifier("defTransactionManager")
public PlatformTransactionManager defTransactionManager() {
    return new HibernateTransactionManager(defSessionFactory().getObject());
}

@Bean
@Qualifier("secondSessionFactory")
public LocalSessionFactoryBean secondSessionFactory() {
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
    sfb.setDataSource(secondDataSource());

    Properties props = new Properties();
    //...

    sfb.setHibernateProperties(props);
    sfb.setPackagesToScan("my.package.subpackage");

    return sfb;
}

@Bean
@Qualifier("secondTM")
public PlatformTransactionManager secondTransactionManager() {
    return new HibernateTransactionManager(secondSessionFactory().getObject());
}
}

我的意图是使用两个事务管理器的注释事务.
Methonds注释如下

@Transactional
public void method() {}

应该由defTransactionManager处理

并且方法注释如下

@Transactional("secondTM")
public void anotherMethod() {}

通过secondTransactionManager

defTransactionManager工作正常但是当涉及到anotherMethod()时,我得到:

org.hibernate.HibernateException: No Session found for current thread

当我对anotherMethod使用程序化事务管理(autowire secondSessionFactory,使用TransactionTemplate)时,一切正常.

最佳答案 如果
@EnableTranscationManagement Spring将使用按类型查找,您可以为单个事务管理器提供自己的查找方法,但是
it will not work for two tx managers

如果要检查Spring如何确定要执行的事务,可以尝试调试TransactionAspectSupport类.关键方法是setTransactionManagerBeanName和determineTransactionManager.

点赞