MyBatis Plus-7-Plug-in Extension

Keywords: Programming SQL Mybatis xml Spring

Plug-in Extension

1.1 Introduction to Mybatis Plug-in Mechanism

1.1.1 Plug-in mechanism:

Mybatis can intercept the execution of the four object-related methods through the plug-in (Interceptor), and complete the dynamic change of relevant data according to the needs.

Executor
StatementHandler
ParameterHandler
ResultSetHandler

1.1.2 Plug-in Principle

Each object of the four major objects is created by executing interceptorChain.pluginAll(), which passes through the plugin() method of each plug-in object in order to create proxies for the current four major objects. The proxy object can intercept the execution of the four object-related methods, because the methods to execute the four objects need to be proxied.

2.1 Paging Plug-in

com.baomidou.mybatisplus.plugins.PaginationInterceptor

Add plug-ins

<plugins>
    <!--
     | Paging plug-in configuration
     | The plug-in provides two dialect choices: 1. Default dialect 2. Custom dialect implementation class. If neither is configured, an exception is thrown!
     | Overflow Current overflows the total number of pages, setting the default false on the first page
     | Optimize Type Count optimization (version 2.0.9 instead of jsqlparser configuration)
     | -->
    <! - Note!!! If you want to support secondary cache paging using the Cache Pagination Interceptor defau lt, the suggestions are as follows!! >
    <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
        <property name= "sqlParser" ref= "Custom parsing class, can you?" />
        <property name="localPage" value="page Heper support is enabled by default false instead of true"/>
        <property name= "dialectClazz" value= "Custom dialect class, can you?" />
    </plugin>
</plugins>

perhaps

@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    /**
     * jPaginate
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

test

public class TestMP01 {

    private ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

    private EmployeeMapper employeeMapper = ctx.getBean("employeeMapper", EmployeeMapper.class);

    /**
     * Test Paging Plug-in
     */
    @Test
    public void testPage() {
        Page<Employee> page = new Page<>(1, 1);

        List<Employee> emps = employeeMapper.selectPage(page, null);

        System.out.println(emps);

        System.out.println("Total number of entries:" + page.getTotal());
        System.out.println("CurrentPage: " + page.getCurrent());
        System.out.println("PP or P:" + page.getPages());
        System.out.println("Number of items displayed per page:" + page.getSize());
        System.out.println("Is there a previous page?: " + page.hasPrevious());
        System.out.println("Is there the next page?: " + page.hasNext());

        //Encapsulate the results of the query into the page object
        page.setRecords(emps);
    }
}

Result implementation

 Preparing: SELECT id AS id,last_name AS lastName,email,gender,age,version FROM tbl_employee LIMIT 0,1

3.1 Executive Analysis Plug-in

com.baomidou.mybatisplus.plugins.SqlExplainInterceptor
  1. SQL execution analysis interceptor only supports MySQL version 5.6.3 or above
  2. The function of this plug-in is to analyze the DELETE UPDATE statement and prevent the whole table operation of DELETE UPDATE by whitewash or malicious.
  3. It is only recommended to use in the development environment, not in the production environment.
  4. At the bottom of the plug-in, the command is analyzed by SQL statement: Explain analyzes the current SQL statement, and determines whether the current full table operation is based on the Extra column in the result set.

Add plug-ins

    <!-- Register Execution Analysis Plug-in -->
    <bean class="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor">
        <property name="stopProceed" value="true"/> <!--Stop or not-->
    </bean>
  • Parameter: stopProceed finds whether execution of the full table delete update statement stops execution

4.1 Performance Analysis Plug-in

com.baomidou.mybatisplus.plugins.PerformanceInterceptor
  • Performance analysis interceptor for output of each SQL statement and its execution time
  • SQL performance analysis, development environment use, more than the specified time, stop running. Help identify problems

Add plug-ins

    <!-- Register Performance Analysis Plug-in -->
    <bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
        <property name="format" value="true"/><!--Format SQL-->
        <property name="maxTime" value="5"/><!--Company ms-->
    </bean>

perhaps

//Spring boot approach
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    /**
     * SQL Execution Efficiency Plug-in
     */
    @Bean
    @Profile({"dev","test"})// Set up dev test environment to open
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
}

5.1 Optimistic Lock Plug-in

com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor
  • If you want to achieve the following requirements: when you want to update a record, you want it not to be updated by others
  • The realization principle of optimistic lock:
    • When the record is taken out, get the current version 2
    • When updating, bring this version 2 with you
    • When updating, set version = yourVersion+1 where version = yourVersion
    • If version is not correct, the update fails
  • @Version For annotating entity fields, you must have
    • Special note: support int,Integer,long,Long,Date,Timestamp only

Add plug-ins

    <!-- Register Optimistic Lock Plug-ins -->
    <bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor"/>

perhaps

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

Sample SQL Principle

update tbl_user set name='update',version=3 where id=100 and version=2;

6.1 Hot Loading of XML Files

    Open dynamic loading mapper.xml
  • Configuring multiple Mybatis Mapper Refresh startup bean s with multiple data sources
  • By default, eclipse saves are compiled automatically, and idea has to compile it manually once.

spring configuration

    <bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="mapperLocations" value="classpath*:mybatis/mappers/*/*.xml"/>
        <constructor-arg name="delaySeconds" value="10"/>
        <constructor-arg name="sleepSeconds" value="20"/>
        <constructor-arg name="enabled" value="true"/>
    </bean>

Description of parameters

SqlSession Factory: Session Factory
 mapperLocations:mapper matching path
 enabled: Whether to turn on dynamic loading default: false
 delaySeconds: Delayed Loading Time Unit for Project Start: Default seconds: 10s
 sleepSeconds: refresh interval unit: second default: 20s

Posted by keeB on Wed, 04 Sep 2019 21:13:54 -0700