I have the following piece of code where I am using Spring's @Transactional annotation with JDBC template and it does not rollback a transaction. I have used random file names and table name. I am trying to delete a row for a Foreign key id and then insert a record for the same id in a database table named "data". But when I was testing I am seeing that if there is an error in the insert, the delete does not get rollbacked. I am pretty new to Spring, so any help would be appreciated.
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>
You should try enabling transaction propagation.
You can read more here: https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html#tx-propagation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.