Springboot + mybatis plus transaction management


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配置类
public class MybatisPlusConf {

    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();

    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        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

	public void buy() throws Exception {
        1. 扣钱
        } catch (Exception e) {
        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 ();


} catch (Exception e) {
return  xxx;

Read More: