简体   繁体   中英

Spring @Transactional annotation behaviour

I am building a workflow system, where a service layer - WorkflowServiceImpl , process a document and send notifications to users. There is another service DocumentServiceImpl , which has a method post() method, which internally calls WorkflowServiceImpl.process() method.

@Service 
public class WorkflowServiceImpl implements WorkflowService{

    @Transactional(propagation=Propagation.REQUIRES_NEW, noRollbackFor=WorkflowException.class)
    public void process(WorkflowDocument document) throws WorkflowException {

        Boolean result = process(document);
        if(!result){
            throw new WorkflowException();
        }
    }

    private Boolean process(WorkflowDocument document){
        //some processing on document
        updateDocument();
        sendNotifications();
    }

    private void updateDocument(WorkflowDocument document){
        //some update operation
    }

    private void sendNotifications(WorkflowDocument document){
        //send notifications - insertion operation
    }
}

@Service 
public class DocumentServiceImpl implements DocumentService{

    @Autowired private WorkflowService workflowService;

    @Transactional
    public void post(){

        //some operations

        workflowService.process(document);

        //some other operations
    }
}

As you can see, I have marked

DocumentServiceImpl.post() as @Transactional  
WorkflowServiceImpl.process() as @Transactional(propagation=Propagation.REQUIRES_NEW, noRollbackFor=WorkflowException.class)

I am trying to achieve this :

1. WorkflowServiceImpl.process() method should commit always(update document and send notifications) - whether a WorkflowException is thrown or not
2. DocumentServiceImpl.post() method should rollback, when WorkflowException is thrown 

When I tried using the above transaction configurations

1. When WorkflowException is not thrown, the code worked as expected - committed both WorkflowServiceImpl.process() and DocumentServiceImpl.post() methods
2. When WorkflowException is thrown, the request processing is not completed (I can see the request processing symbol in the browser) 

I can't find what is wrong with the code. I am using spring version 3.1.4

You need to have a rollbackFor in the @Transactional annotation for WorkflowException and propagation as REQUIRES_NEW

@Transactional(rollbackFor = {WorkflowException.class}, propagation = Propagation.REQUIRES_NEW)
public void post(){

    //some operations

    workflowService.process(document);

    //some other operations
}

This will make a new transaction to be started with post method of DocumentServiceImpl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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