Springboot + mybatis plus transaction management

business

transactions are mainly used to process data with large operation volume and high complexity. For example, in the personnel management system, you delete a person, you need to delete the basic information of the person, also want to delete the information related to the person, such as mailbox, article and so on, so that these database operation statements constitute a transaction!

open transaction, in Springboot start class, or a @ the Configuration class with @ EnableTransactionManagement open transactions. Because this is database related, I added

to the mybatis plus configuration class

/**
 * mybatisplus配置类
 */
//扫描mapper文件夹
@MapperScan("com.sec.mapper")
@EnableTransactionManagement//事务
@Configuration//配置类
public class MybatisPlusConf {


    //配置乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    //配置分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setOverflow(false);
        return paginationInterceptor;
    }
}

Then simply add @transactional to the method that needs to use the transaction and start the transaction, just as simple as

notice that

Transactional by default rollback is RuntimeException which means that the database does not roll back if an exception is thrown that is not RuntimeException. Fortunately, however, under the springframework, all exceptions are rewritten by the org.springframework as RuntimeException, so you don't need to worry too much about

and if the exception is caught and handled manually by the programmer, the exception will not be rolled back

@Transactional
	public void buy() throws Exception {
        try{
        1. 扣钱
        } catch (Exception e) {
        	catch了自己处理,也就是异常被自己吞了,外层并不知道,此时也不会回滚
        }
        3. 扣库存
    }

when we need to use a try catch to catch an exception in the service layer class of transaction control, the transaction control is invalidated, because the exception of this class is not thrown, it is not the trigger transaction management mechanism. How to use the try catch to catch exceptions, and let the abnormal after spring roll back, here will use the TransactionAspectSupport. CurrentTransactionStatus (). The setRollbackOnly ();

//假设这是一个service类的片段

try{
    //出现异常
} catch (Exception e) {
            e.printStackTrace();
           //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
        }
//此时return语句能够执行
return  xxx;

Read More: