首页 > 解决方案 > 如何使用 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 配置,事务也在回滚,为什么?

标签: javaspringspring-boothibernatespring-data-jpa

解决方案


我会假设您包含的异常noRollbackFor是在提交时抛出的(当事务拦截器尝试提交当前会话时),自然由于提交是不可能的,事务被回滚。

这意味着 Spring 尊重您不回滚这些异常的请求,但由于它发生在提交阶段,它除了回滚事务并重新抛出异常之外,还可以执行任何其他操作。您对此无能为力 - 这就是@Transactional工作机制。


推荐阅读