我有以下代码,我使用Spring的@Transactional注释和JDBC模板,它不回滚事务。我使用了随机文件名和表名。我试图删除外键id的行,然后在名为“data”的数据库表中插入相同id的记录。但是当我测试时,我看到如果插入中有错误,则删除不会被回滚。 我对Spring很新,所以任何帮助都会受到赞赏。
TestService.java
@Service
public class TestService {
@Autowired
TestRepository testRepository;
@Transactional(rollbackFor={Exception.class})
public void insertData(List<Data> dataList, Integer fkId)
throws Exception {
testRepository.updateData(dataList, fkId);
//do some other stuff
}
}
TestRepository.java
@Respository
public class TestRepository {
@Autowired
@Qualifier("dataJdbcTemplate")
private NamedParameterJdbcTemplate dataJdbcTemplate;
@Transactional(rollbackFor={Exception.class})
public void updateData(List<Data> dataList, Integer fkId)
throws Exception {
String deleteId = "DELETE FROM data where
fk_id = :fkId";
dataJdbcTemplate.update(deleteId, new
MapSqlParameterSource("fkId", fkId));
String sql = "INSERT INTO data(fk_id, column1, column2)"
+ " VALUES(:fkId, :column1, :column2)";
SqlParameterSource[] batch =
SqlParameterSourceUtils.createBatch(dataList.toArray());
dataJdbcTemplate.batchUpdate(sql, batch);
}
database.xml
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.
NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
答案 0 :(得分:0)
您应该尝试启用事务传播。
您可以在这里阅读更多内容: https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html#tx-propagation