2012-08-06 54 views
4

我在基於註釋的配置類配置的兩個事務管理器:多個事務經理註解配置

@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

和方法通過secondTransactionManager註釋這樣

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

處理

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

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

當我爲另一個方法使用編程事務管理(autowire secondSessionFactory,使用TransactionTemplate)時,一切正常。

回答

1

@EnableTranscationManagement春天的情況下將使用類型的查找,您可以提供自己的查詢方法,一個事務管理器,但it will not work for two tx managers

如果你想檢查春季如何確定交易執行,可以嘗試調試TransactionAspectSupport類。關鍵方法是setTransactionManagerBeanNamedetermineTransactionManager

+1

我想到這一點,因爲我的配置類實現TransactionManagementConfigurer和annotationDrivenTransactionManager返回defTransactionManager() – 2012-08-06 13:11:57

+0

@AlexanderCamperov是一個Web應用程序的覆蓋方法? – 2012-08-06 13:13:49

+0

是的,這是一個網絡應用程序。 – 2012-08-06 13:15:19

1

萬一有人運行到這個問題,我找到了一個解決方案:

@Configuration 
@EnableTransactionManagement 
@DependsOn("myTxManager") 
@ImportResource("classpath:applicationContext.xml") 
public class AppConfig implements TransactionManagementConfigurer { 

@Autowired 
private PlatformTransactionManager myTxManager; 

... 

@Override 
public PlatformTransactionManager annotationDrivenTransactionManager() { 
    return this.myTxManager; 
} 

通過這種方式,您可以使用XML配置定義的特定txManager。

如果你要定義的txManager服務級別時,你應刪除@Configuration@EnableTransactionManagement註釋,並在註釋@Transactional指定txManager,例如

@Service 
@Transactional(value="myTxManager", readOnly = true) 
public class MyServiceImpl implements MyService { ... }