java - 如何使用 spring-data/jpa 忽略“重复条目”异常
问题描述
@Transactional(noRollbackFor = {SQLIntegrityConstraintViolationException.class, ConstraintViolationException.class, DataIntegrityViolationException.class})
public void createLead(List<Info> infos)
{
for (Info info : infos)
{
try
{
repo.save(info.toDao());
}
// should catch Duplicate entry (SQLIntegrityConstraintViolationException, ConstraintViolationException, DataIntegrityViolationException)
catch (Throwable ignore)
{
}
}
}
List<Info>
如果有任何错误(发生错误除外),我想将所有内容插入数据库并回滚duplicate entry
,但即使使用 try/catch 和 noRollbackFor 配置,事务也在回滚,为什么?
解决方案
我会假设您包含的异常noRollbackFor
是在提交时抛出的(当事务拦截器尝试提交当前会话时),自然由于提交是不可能的,事务被回滚。
这意味着 Spring 尊重您不回滚这些异常的请求,但由于它发生在提交阶段,它除了回滚事务并重新抛出异常之外,还可以执行任何其他操作。您对此无能为力 - 这就是@Transactional
工作机制。
推荐阅读
- c# - 使用列表保存多个复选框的状态
- python - 使用已排序按字母数字值对列进行排序
- python - 将两个具有外键关系的模型数据传递给一个 html 模板
- python - 提交按钮没有点击 selenium python?
- arel - 如何将 `matches()` 与数据库函数一起使用?
- git - 如何推送一次并取消跟踪?
- google-drive-api - 如何确定更改是通过 API 发生的还是由人为发生的?
- entity-framework-core - EF Core 并以最佳方式加载相关数据
- python - 为什么此代码在一种情况下有效,而在另一种情况下无效?
- angular - Angular Material MatSort 和sortingDataAccessor 如何协同工作?