我必須開發一個在Spring中使用兩個數據源的應用程序。這兩個數據源應該由事務管理,以便在一個數據源中發生一些異常時,另一個數據源也應該回滾。我現在的發言是,我目前使用jta植入不起作用。當我測試我的代碼時,如果一個數據源出錯,另一個數據源不會回滾。它只是承諾。 這裏是我的配置文件:在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;
}
});
}
}
誰能告訴我問題出在哪裏?