简体   繁体   中英

Communication to caller of method annotated @Transactional

I have a method on which I am using the Spring @Transactional annotation:

    @Transactional
    public void persistAmendments(int _cutsheetId) {
          ...
    }

If a condition occurs which forces a rollback of this transaction, how will a caller of persistAmendments() know about this? I would like my calling code to handle the situation appropriately. Is there a special exception that is thrown up the stack?

The method calling your persistence layer will catch any RuntimeExceptions, and that will let it know that you had an error while persisting the data. Spring by default rolls back any transaction that throws a RuntimeException. Here is an abbreviated example of what I mean.

AmendementService

@Service
public class AmendmentService {

    @Autowired
    private AmendmentRepository amendmentRepository;

    public boolean persistAmendments(int _cutsheetId) {
        boolean persistSuccessful = true;
        try {
            amendmentRepository.persistAmendments(_cutsheetId);
        } catch (RuntimeException e) {
            persistSuccessful = false;
        }
        return persistSuccessful;
    }
}

AmendmentRepository

@Repository
public class AmendmentRepository {

    @Transactional
    public void persistAmendments(int _cutsheetId) {
        //attempt to persist
    }

}

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