Spring有两个事务管理器,另一个在另一个内

时间:2016-11-07 07:46:17

标签: java spring transactions

我在上下文文件中定义了两个事务管理器,如下所示

<tx:annotation-driven transaction-manager="firstTransactionManager" />

   <bean id="secondDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="---" />
    <property name="url" value="datasource1" />
    <property name="username" value="----" />
    <property name="password" value="----" />
</bean>
    <bean id="firstTransactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="firstDataSource" />
    <qualifier value="firstTxManager"/>
</bean>


<bean id="secondTransactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="secondDataSource" />
    <qualifier value="secondTxManager"/>
</bean>

<bean id="firstDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="---" />
    <property name="url" value="datasource2" />
    <property name="username" value="---" />
    <property name="password" value="---" />
</bean>

我的课程定义如下

@Transactional("firstTransactionManager")
public class JdbcMain {
@Autowired
private static DataSource dataSource;
public DataSource getDataSource() {
    return dataSource;
}
public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}
public static void main(String args[]){
       ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

       TransactionExample example = (TransactionExample) ctx.getBean("transExample");


       example.create();

}

}

我的示例类如下:

@Transactional("secondTransactionManager")
public void create(DataSource dataSource2) {


try {

    this.jdbcTemplate = new JdbcTemplate(dataSource2);
    String sql = "insert into testtable values (?,?)";
    getJdbcTemplate().update(sql,1,"1244343");
    String marksSql="insert into testtable values (?,?)";
        int i=2/0; //added to depict roll back behaviour of the transaction when exception occurs
                          getJdbcTemplate().update(marksSql,2,"sujay");

            System.out.println("transaction committed");
        } catch (RuntimeException e) {
          throw e;

        }
    }

但是第二个事务管理器似乎没有工作,并且事务没有回滚(执行第一个插入)。你能给我一个想法吗?

0 个答案:

没有答案