在我的应用程序中,我有 2 个 transactionManager,创建如下:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<qualifier value="exec"/>
<property name="dataSource" ref="execDataSource"/>
</bean>
<bean id="txManagerAdmin" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<qualifier value="admin"/>
<property name="dataSource" ref="adminDataSource"/>
</bean>
在同一个文件中,我有注释驱动的声明:
<tx:annotation-driven transaction-manager="admin"/>
为了简化我的管理事务管理器的可用性,我创建了一个简单的注释:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(value="admin", rollbackFor=NullPointerException.class, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT)
public @interface AdminTx {
}
这里是我的带有事务注释的方法:
@AdminTx
@Override
public UaCatalogDTO addUa(UaDTO uaDTO) throws TechnicalException {
MapSqlParameterSource namedParameterSource = new MapSqlParameterSource();
mapAllUaFields(uaDTO, namedParameterSource);
try {
jdbcTemplate.update(SqlQueries.ADD_UA, namedParameterSource);
} catch (DuplicateKeyException e) {
throw new TechnicalException(e, "ADM001");
}
if (1==1) //due to compiler
throw new NullPointerException(); //to test the transaction is working
}
由于接口,此方法从另一个类调用。bean 是由 Spring @Autowired 注解注入的。该jdbcTemplate
对象是使用以下代码创建的:
@Autowired
@Qualifier("adminDataSource")
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
我的问题是当我执行该jdbcTemplate.update()
行时,如果我检查我的数据库,数据已经存在。另外,即使我抛出 NullPointerException,数据也会保留在数据库中。
经过一番搜索,我发现我们可以调用TransactionSynchronizationManager.isActualTransactionActive()
,它返回我false
的值。所以我知道我的注释什么也没做,但我不明白为什么。
我在 Websphere 服务器上运行,数据库是 DB2。