我必须开发一个在 Spring 中使用两个数据源的应用程序。这两个数据源应该由一个事务管理,这样如果一个数据源发生异常,另一个数据源也应该回滚。我现在的问题是我目前的 jta 植入不起作用。当我测试我的代码时,如果一个数据源有错误,另一个数据源没有回滚。它只是承诺。这是我的配置文件:
<bean id="parentDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
abstract="true">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
</bean>
<bean id="firstDataSource" parent="parentDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
</bean>
<bean id="secondDataSource" parent="parentDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/test2"/>
</bean>
<bean id="jtaTransactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
</bean>
<bean id="customerDAO" class="springapp.datasource.CustomerDAO">
<property name="dataSource">
<ref local="firstDataSource"/>
</property>
<property name="dataSource2">
<ref local="secondDataSource"/>
</property>
<property name="jtaTransactionManager">
<ref local="jtaTransactionManager"/>
</property>
</bean>
customerDAO 中的交易代码为:
public class CustomerDAO {
private DataSource dataSource;
private DataSource dataSource2;
private JtaTransactionManager jtaTransactionManager;
public DataSource getDataSource2() {
return dataSource2;
}
public void setDataSource2(DataSource dataSource2) {
this.dataSource2 = dataSource2;
}
public JtaTransactionManager getJtaTransactionManager() {
return jtaTransactionManager;
}
public void setJtaTransactionManager(JtaTransactionManager jtaTransactionManager) {
this.jtaTransactionManager = jtaTransactionManager;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insertItem(Item item){
TransactionTemplate tt = new TransactionTemplate(jtaTransactionManager);
tt.execute(new TransactionCallback<Object>(){
@Override
public Object doInTransaction(TransactionStatus arg0) {
JdbcTemplate jt = new JdbcTemplate(dataSource);
String sql = "insert into item(name,price) values ('aaaa',11);";
jt.setDataSource(dataSource);
jt.update(sql);
sql = "insert into item(name,price) values ('aaaa',12);";
jt.setDataSource(dataSource2);
jt.update(sql);
return null;
}
});
}
}
谁能告诉我问题出在哪里?