How to implement transaction rollback with @Transaction…
In Spring, we can use the @Transactional annotation to start a transaction. When a method is marked as @Transactional, if an exception occurs or specific exceptions are thrown during the method execution, the transaction will be rolled back.
To achieve transaction rollback, you can follow these steps:
- Enable transaction manager in the Spring configuration file.
- Create a bean called “transactionManager” of class “org.springframework.jdbc.datasource.DataSourceTransactionManager” with a property “dataSource” referencing “dataSource”. Enable annotation-driven transactions using the specified transaction manager “transactionManager”.
- Add the @Transactional annotation to the method that requires transaction management.
- – The database operation will be executed within a transactional method, and if an exception occurs, the transaction will roll back.
If an exception occurs during the execution of the method someTransactionalMethod(), the transaction will be rolled back, undoing any previous operations.
By default, the @Transactional annotation will rollback exceptions of RuntimeException and its subclasses. If you want to rollback other types of exceptions, you can use the rollbackFor attribute to specify the types of exceptions that need to be rolled back.
@Transactional(rollbackFor = Exception.class)
public void someTransactionalMethod() {
// 执行数据库操作
// 如果发生异常,事务将会回滚
}
By following the steps above, you can achieve transaction rollback using the @Transactional annotation in Spring.