sqlintegrityconstraintviolationexception导致spring事务回滚

bhmjp9jg  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(539)

spring 4.1.4 hibernate 4.2.0 jdk 1.8版
我的上下文:我有一个控制器调用-->服务-->调用dao业务功能是删除(在1对多db关系中)一些子级,但不是全部子级。然后,在删除一些子级之后,我尝试删除父级,当然我得到了java.sql.sqlintegrityconstraintviolationexception
但问题是,为什么交易是市场的回退换句话说,为什么我没有删除某个孩子?)
sqlintegrityconstraintviolationexception是一个选中的异常,说明spring文档的行为与ejb相同:注意,默认情况下,回滚只发生在运行时,未选中的异常。选中的异常不会触发事务的回滚。
我需要删除一些子对象,如果可能的话,我需要删除父对象,如果没有,我需要提交事务,维护父对象和剩余的子对象注意,我还尝试在服务和dao方法中指定spring注解

@Transactional(noRollbackFor = SQLIntegrityConstraintViolationException.class)

明确要求我的行为,但我甚至不喜欢这样的工作
控制器代码方法:

public void delete() {
    FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Data deleted.","");

    try{
        memoTemplateService.delete(memoTemplate);
        memoTemplates.remove(memoTemplate);
    }
    catch (Exception e){
        msg=new FacesMessage(FacesMessage.SEVERITY_WARN, "A","B");
    }
    reset();

    FacesContext.getCurrentInstance().addMessage(null, msg);
}

服务方式:

@Override
@Transactional(noRollbackFor =  {SQLIntegrityConstraintViolationException.class,DBConstraintException.class})
public void delete(MemoTemplate memoTemplate)throws BusinessException {
    // deleting some ,not all , child 
    phaseAndMemoGenerator.deleteMemosForVisibleTimeHorizon(memoTemplate);
    try{// some times Template cannot be deleted
        memoTemplateDao.delete(memoTemplate);
    }
    catch (Exception e){
        throw new DBConstraintException("Partial Delete", "Template cannot be deleted, Memo in the past are present");
    }
}

@Repository(value = "memoTemplateDao")
public class MemoTemplateDaoImpl extends GenericJpaDaoImpl<MemoTemplate,  Long> implements MemoTemplateDao {

@Override
@Transactional(noRollbackFor = SQLIntegrityConstraintViolationException.class)
public void delete(MemoTemplate t) {
    super.delete(t);
    em.flush();
}
}

只是一个更新:这是难以置信的,但我也不能在dao方法中捕获,调试器进入catch块,但在此之前,仍然会触发java.sql.sqlintegrityconstraintviolationexception,难以置信!

@Transactional(noRollbackFor = {SQLIntegrityConstraintViolationException.class,PersistenceException.class})
public void tryToDelete(MemoTemplate t)throws Exception {
    super.delete(t);
    try{
        em.flush();
    }
    catch (Exception e){
        throw new Exception("ddddd");
    }
}
8qgya5xd

8qgya5xd1#

如果在db中定义了约束,那么您将无法通过提交而不回滚来绕过它们。

相关问题