简体   繁体   English

当异常在子方法中抛出时,事务不会回滚 - Spring

[英]Transaction not getting rolled back for when exception throws in child method - Spring

I have a method Service method - SampleServiceImpl().我有一个方法服务方法 - SampleServiceImpl()。 I have declared the Service method as following:我已将 Service 方法声明如下:

@Transactional
@Override
public sampleDTO SampleServiceImpl(SampleDTO sampleDTO) throws SampleException, ParseException { 
   // Method call to methodA.
   createDataA(sampleDTO);
   // Method call to methodB.
   createDataB(sampleDTO);

   return sampleDTO ;
}

Here the DataA is created and it does not throw any exception.这里创建了 DataA 并且它不会抛出任何异常。 But in DataB, we are trying to create DataB based on DataA.但是在DataB中,我们试图基于DataA创建DataB。 Due to some logic, we cannot create DataB.由于某些逻辑,我们无法创建DataB。 So, we throw a Sample Exception like:所以,我们抛出一个示例异常,如:

count = checkIfDataBExisting(sampleDTO);
if(count == 1){
   throw new SampleException(ErrorConstants.DATA_B_EXISTING);
}

But the problem is, the transaction that got committed during createDataA(sampleDTO) method call, does not get rolled Back.但问题是,在createDataA(sampleDTO)方法调用期间提交的事务不会回滚。

Why does this don't actually work?为什么这实际上不起作用? I'm bit confused with this behavior.我对这种行为有点困惑。

EDIT:1编辑:1

createData1(sampleDTO) method - createData1(sampleDTO) 方法 -

private ADTO createDataA(SampleDTO sampleDTO) throws SampleException{
    ADTO aDTO = null;    
    try {
        //CREATE NEW WORK DRIVER
        aDTO = createNewDataA(sampleDTO);

        //Other arbitary database transactions occurs after creation of AData.


} catch (SampleException exc) {
    SampleException newException = new SampleException (exc.getExceptionObject().getExceptionCode(), exc);

    throw newException ;
}
return aDTO;
}

EDIT2:编辑2:

SampleException Declaration -示例异常声明 -

public class SampleException extends Exception{
    //Definitions and Declarations.
}

By default declarative transactions rollback only for Runtime exceptions.默认情况下,声明性事务仅针对运行时异常回滚。 SampleException has to be RuntimeException for the Transaction to be rolled back. SampleException 必须是 RuntimeException 才能回滚事务。

Your method signature:您的方法签名:

public sampleDTO SampleServiceImpl(SampleDTO sampleDTO) throws SampleException, ParseException

makes me think that SampleException is a checked one.让我觉得 SampleException 是一个检查过的。

See the documentation for @Transactional :请参阅@Transactional文档

If no rules are relevant to the exception, it will be treated like DefaultTransactionAttribute (rolling back on RuntimeException and Error but not on checked exceptions).如果没有与异常相关的规则,则将其视为 DefaultTransactionAttribute(回滚 RuntimeException 和 Error 但不回滚已检查的异常)。

You can either make SampleException extends RuntimeException or set the rollbackFor attribute of @Transactional .您可以使SampleException扩展RuntimeException或设置@TransactionalrollbackFor属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM