What are the methods for committing and rolling back transactions in Spring?

In Spring, transaction submission and rollback are achieved through either programmatic transaction management or declarative transaction management.

  1. Programmatic transaction management involves handling the commit and rollback of transactions in the code itself, usually done using the TransactionTemplate class. Here is an example code snippet:
@Autowired
private PlatformTransactionManager transactionManager;

public void doSomething() {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.execute(status -> {
        // 执行业务逻辑
        // 如果需要回滚,可以通过status.setRollbackOnly()来设置回滚
        return null;
    });
}
  1. Declarative transaction management:
    By using the @Transactional annotation or XML configuration to declare transaction attributes, Spring will begin a transaction before the method is executed, and automatically commit or rollback the transaction based on the result of the method execution after it is done. An example code is shown below:
@Transactional
public void doSomething() {
    // 执行业务逻辑
}

In the above two methods, if the method executes normally, the transaction will be automatically committed; if an exception is thrown in the method, the transaction will be automatically rolled back. Additionally, programmatic transaction management allows manual setting of the transaction rollback status.

Leave a Reply 0

Your email address will not be published. Required fields are marked *