为了避免死锁,我想逐行更新一个 id 列表。为了在春季回滚数据,我使用了注释事务。但是当我测试事务时,当更新sql抛出异常时,它并没有从之前更新的记录中回滚数据。这是我的代码:
@Service
public class YahooBudgetUpdateService {
@Autowired
private AccounttUpdateMapper mapper;
public void accountUpdate() throws Exception {
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
updateAcnt(ids);
}
@Transactional
public void updateAcnt(List<String> ids) throw Exception {
for(int i=0; i<ids.size; i++){
updateById(ids.get(i));
}
}
}
Mapper.java:
public interface AccountUpdateMapper {
int updateById(String id);
}
映射器.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="src.mapper.AccountUpdateMapper">
<update id="updateById">
UPDATE ad_cpnt
SET
updatedOn = now(),
lst_updtd_dt= now(),
where
id = #{id}
</update>
</mapper>
我尝试使用 @Transactional(rollbackFor= {Exception.class}) 但它也不起作用。有人知道原因吗?
答案 0 :(得分:1)
这里是所有可以工作的东西
Service
public class YahooBudgetUpdateService {
@Autowired
private AccounttUpdateMapper mapper;
@Transactional <-----This belongs here as it will not work with internal calls as explained in comments
public void accountUpdate() throws Exception {
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
updateAcnt(ids);
}
public void updateAcnt(List<String> ids) throw Exception {
for(int i=0; i<ids.size; i++){
mapper.updateById(ids.get(i)); <-----here you must invoke it from mapper instance not another internal call
}
}
}