与注释@Transactional的方法的调用者通信

时间:2015-05-15 18:47:23

标签: java spring transactions

我有一个方法,我正在使用Spring @Transactional注释:

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

如果出现强制回滚此事务的情况,persistAmendments()的调用者将如何知道这一点?我希望我的调用代码能够恰当地处理这种情况。是否有一个特殊的异常被抛出堆栈?

1 个答案:

答案 0 :(得分:1)

调用持久层的方法将捕获任何RuntimeExceptions,这会让它知道在保存数据时出错。默认情况下,Spring会回滚抛出RuntimeException的任何事务。这是我的意思的缩写示例。

<强> 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
    }

}