spring programmatic and declarative transactions

Posted by PABobo on Sun, 09 Jan 2022 05:13:46 +0100

catalogue

Programming transaction

Simple case

TransactionTemplate

 PlatformTransactionManager

Declarative transaction

Simple use

Simple example

@Transactional common properties

Transaction propagation behavior

Points needing attention

Programming transaction

Programmed transaction management is intrusive transaction management, using TransactionTemplate or directly using platform transactionmanager. For programmatic transaction management, Spring recommends using TransactionTemplate.

Simple case

TransactionTemplate

@Configuration
public class MyPlatformTransactionManager {
    @Bean
    public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager){
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(platformTransactionManager);
        return transactionTemplate;
    }
}
    @Autowired
    TransactionTemplate transactionTemplate;
    

    @Override
    public int insertTran(int id, String username, String password) {
        Integer p = transactionTemplate.execute(status -> {
            userService.insertTran(8, "dd", "ff");
            userService.insertTran(9, "dd", "ff");
            userService.insertTran(10, "dd", "ff");
            int i = userService.insertTran(id, username, password);
            return i;
        });
        return p;
    }

 PlatformTransactionManager

    @Autowired
    private PlatformTransactionManager txManager ;

    //Template
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = txManager.getTransaction(def);
        int result = 0;
        try {
            result=//dosomething
            txManager.commit(status);
        }catch (Exception e){
            txManager.rollback(status);
        }
        return result;

Declarative transaction

Declarative transaction management is based on AOP. Its essence is to intercept before and after the method, then create or join a transaction before the start of the target method, and commit or rollback according to the execution after the target method is executed.

Simple use

The first step is to enable annotation support

@EnableTransactionManagement

The second step is to add transaction management annotations to the service layer where transaction management is desired

@Transactional

Simple example

Take the simplest insert statement as an example. We want to implement multiple inserts. As long as one insert is unsuccessful, we will roll back all inserts.

Just use @ Transactional on the inserted method

    @Override
    @Transactional
    //An arbitrary insertion is simulated. The id is the primary key. If the id has repeated exceptions, all are rolled back
    public int insertTran(int id, String username, String password) {
        userService.insertTran(5,"dd","ff");
        userService.insertTran(6,"dd","ff");
        userService.insertTran(7,"dd","ff");
        int i = userService.insertTran(id, username, password);
        return i;
    }

@Transactional common properties

Propagation: propagation behavior of transactions. The default value is REQUIRED.

Isolation: the isolation degree of the transaction. The DEFAULT value is DEFAULT.

Timeout: the timeout time of the transaction. The default value is - 1. There is no timeout. If the timeout time (in seconds) is set, if the time limit is exceeded but the transaction has not completed, the transaction will be rolled back automatically.

Read only: Specifies whether the transaction is read-only. The default value is false; To ignore methods that do not require transactions, such as reading data, you can set read only to true.

Rollback for: used to specify the exception types that can trigger transaction rollback. If multiple exception types need to be specified, each type can be separated by commas. {xxx1.class, xxx2.class,……}

noRollbackFor: throws the exception type specified by no rollback for and does not roll back the transaction. {xxx1.class, xxx2.class,……}

Transaction propagation behavior

When we execute a transaction method, the other side also executes the method. Then we have to deal with it through transaction propagation at this time.

Points needing attention

  • We usually don't write @ Transactional on the interface
  • @Transactional can only be used on public methods
  • @Methods marked with Transactional are not rolled back if they are not run-time exceptions
  • If we throw an Exception (non runtime Exception) upward, we can specify the rollbackFor attribute to roll back

Topics: Java Spring Back-end