Last time we looked at mybatis- Plus code generator, this time we will look at mybatis- Plus extension of the plugin.
First let’s review the Mybatis plugin mechanism:
- Plug-in mechanism: Mybatis through the plug-in (Interceptor) can intercept the implementation of the four object related methods, according to the needs, complete the relevant data dynamic change. Executor StatementHandler ParameterHandler ResultSetHandler
- Plug-in principle: four object of each object is created, will perform interceptorChain. PluginAll (), passes through each plug-in objects plugin () method, the purpose is for the current four big object creation agent. A proxy object can intercept the execution of the methods associated with the four objects, because the methods that execute the four objects need to pass through the proxy.
Mybatis – Plus has three plugins, and you can try them yourself:
- Paging plug-in
- Execute analysis plug-in
- Optimistic lock plug-in
You can copy all the content in MP05 by creating an MP06 Module as described in the quick Start – Spring Integration with Mybatis-Plus section.
Modify mp06 pom. XML file:
<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < the parent > < artifactId > mybatis - plus - in - action < / artifactId > < groupId > com. The demo. Mybatis - plus < / groupId > < version > 1.0 - the SNAPSHOT < / version > </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mp06</artifactId> <dependencies> <! Mybatis- plus will automatically maintain mybatis and mybatis-spring dependencies. Please do not add mybatis-spring dependencies to mybatis-spring dependencies. Mybatis-Plus will automatically help you maintain! --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatis.plus.version}</version> </dependency> <! --junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <! -- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <! -- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <! -- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <! -- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <! --lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <! Note: MyBatis-Plus removed the default dependencies on the code generator and template engine from 3.0.3, requiring manual addition of dependencies: --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>${mybatis.plus.version}</version> </dependency> <! The template engine MP code generator uses Apache's Velocity template by default, but can be replaced by other templating technologies such as Freemarker. I won't go into too much here. <dependency> <groupId>org.apache. Velocity </groupId> <artifactId>velocity-engine-core</artifactId> <version>${velocity.version}</version> </dependency> <! Slf4j </groupId> <artifactId> slf4J-api </artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies> </project>Copy the code
Here are some changes we need to make for different plugins:
1. Paging plug-ins
We actually showed the paging plug-in in the previous paging query code example, but it wasn’t introduced at the time, so let’s look at it in more detail.
We can configure paging in two ways:
1.1. Modify mybatis-config. XML file and add paging plug-in
<! -- 1. The first way, Mybatis -config. XML file -> <plugins> <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin> </plugins>Copy the code
The complete mybatis-config.xml file is as follows:
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <! -- 1. The first way, Mybatis -config. XML file -> <plugins> <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin> </plugins> </configuration>Copy the code
1.2. Modify the applicationContext. XML file and add a paging plug-in
In the sqlSessionFactory bean, the plugins are configured with
<! <property name="plugins"> <list> <! - paging query plugin - > < bean id = "paginationInterceptor" class = "com. Baomidou. Mybatisplus. The extension. Plugins. PaginationInterceptor" > <property name="dialectType" value="mysql"/> </bean> </list> </property>Copy the code
1.3. Test the paging plug-in
Either of the 1.1 and 1.2 methods can be used to implement paging. Now let’s add the following code to the TestMp test class to test the functionality of the paging plug-in
/ * * * Test Page plug-in * / @ Test public void testPage () {IPage < Employee > employeeIPage = employeeMapper. SelectPage (new Page < > (2, 1), null); Println ("employeeIPage: "+ employeeiPage.getRecords ()); system.out.println ("employeeIPage:" + employeeiPage.getRecords ()); }Copy the code
2. Execute the analysis plug-in
The purpose of this plug-in is to analyze DELETE UPDATE statements and prevent DELETE UPDATE full table operations. At the bottom of the plug-in through SQL statement analysis command :Explain analysis of the current SQL statement, according to the Extra column in the result set to determine whether the current full table operation.
Note: This is recommended for development environments only, not production environments. SQL execution analysis interceptor, only MySQL5.6.3 and above is supported.
2.2. Modify the applicationContext. XML file and add the execution analysis plug-in
<! Execution analysis plug-ins are only recommended for use in development environments, In a production environment is not recommended to use -- - > < bean class = "com. Baomidou. Mybatisplus. The extension. Plugins. SqlExplainInterceptor" > < property name="sqlParserList"> <! On a full table delete - > < bean class = "com. Baomidou. Mybatisplus. The extension. Parsers. BlockAttackSqlParser" > < / bean > < / property > < / bean >Copy the code
2.2 test execution analysis plug-in
Let’s test our execution analysis plug-in by performing a full table drop, adding the following code to the test class:
// @test public void testSqlExplain() {// Delete employeemapper.delete (null); }Copy the code
Mysql > select * from testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest;
3. Optimistic lock plug-in
Thinking about? If you want to implement the following requirement: When you want to update a record, you want the record not to be updated by others. When we want to implement the above requirements, the first thing that comes to mind is to use optimistic locking.
The principle of optimistic locking is as follows: 3) Set version = yourVersion+1 where version = yourVersion Update failed
3.1. Modify applicationContext. XML file and add optimistic lock plug-in
To use the optimistic lock plugin provided by Mybatis-Plus, you first need to modify the applicationContext. XML file to add the optimistic lock plugin
<! -- Optimistic lock plugin. When doing this test, you need to attach a version field to the entity class. The corresponding also need the field is added to the database - > < bean class = "com. Baomidou. Mybatisplus. The extension. Plugins. OptimisticLockerInterceptor" > < / bean >Copy the code
3.2. Modify the Employee entity class
Modify the Employee entity class to add a Version field and getter and setter methods
@Version
private Integer version;
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
Copy the code
3.3. Test the optimistic lock plug-in
Add the following code to the test class:
*/ @test public void testOptimisticLocker() {Employee Employee = new Employee(); employee.setId(10); employee.setLastName("MP"); employee.setAge(25); employee.setEmail("[email protected]"); employee.setGender("0"); employee.setVersion(2); ! [mp06-02.png](https://upload-images.jianshu.io/upload_images/19878305-e8348cc75321c5f1.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) employeeMapper.updateById(employee); }Copy the code
After executing this method, we will see that the test method executed successfully. When updating, we will bring this version, but the updated data is 0, indicating that the data in the database has not been updated.
After doing this, the complete applicationContext.xml file for MP06 looks like this:
<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" Xsi: schemaLocation = "HTTP: / / http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <! -- dataSource --> <context: property.placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <! - the transaction manager - > < bean id = "dataSourceTransactionManager." class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <! - annotation-based transaction management - > < tx: annotation - driven transaction - manager = "dataSourceTransactionManager" / > <! - configuration SqlSessionFactoryBean mybatis provides: org. Mybatis. Spring. SqlSessionFactoryBean mybatis - plus provides: 3.2.0 com. Baomidou. Mybatisplus. The extension. Spring. MybatisSqlSessionFactoryBean 2.3 com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean --> <bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <! </property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <! <property name="typeAliasesPackage" value="com.mp.beans"></property> <! -- Injection configuration --> <! --<property name="configuration" ref="configuration"></property>--> <! <property name="globalConfig" ref="globalConfiguration"></property> <! <property name="plugins"> <list> <! - paging query plugin - > < bean id = "paginationInterceptor" class = "com. Baomidou. Mybatisplus. The extension. Plugins. PaginationInterceptor" > <property name="dialectType" value="mysql"/> </bean> <! Execution analysis plug-ins are only recommended for use in development environments, In a production environment is not recommended to use -- - > < bean class = "com. Baomidou. Mybatisplus. The extension. Plugins. SqlExplainInterceptor" > < property name="sqlParserList"> <! On a full table delete - > < bean class = "com. Baomidou. Mybatisplus. The extension. Parsers. BlockAttackSqlParser" > < / bean > < / property > < / bean > <! -- Optimistic lock plugin. When doing this test, you need to attach a version field to the entity class. The corresponding also need the field is added to the database - > < bean class = "com. Baomidou. Mybatisplus. The extension. Plugins. OptimisticLockerInterceptor" > < / bean > </list> </property> </bean> <! - this is equal to Mybatis global configuration file, if have configured in MybatisSqlSessionFactoryBean configLocation attributes (external load Mybatis global configuration file), Can't configure the configuration properties - > < bean id = "configuration" class = "com. Baomidou. Mybatisplus. Core. MybatisConfiguration" > <! <property name="mapUnderscoreToCamelCase" value="true"/> <! - log print SQL statements -- > < property name = "logImpl" value = "org. Apache. Ibatis. Logging. Log4j. Log4jImpl" > < / property > < / bean > <! - define mybatis - plus global policy configuration - > < bean id = "globalConfiguration" class = "com. Baomidou. Mybatisplus. Core. Config. GlobalConfig" > <! <property name="dbConfig" ></property> </bean> <! -- -- -- > < bean id = "dbConfig" class = "com. Baomidou. Mybatisplus. Core. Config. GlobalConfig $dbConfig" > <! <property name="idType" value="AUTO"></property> <! <property name="tablePrefix" value="tbl_"></property> </bean> <! - configure the path of scanning mybatis mapper interfaces - > < bean class = "org. Mybatis. Spring. Mapper. MapperScannerConfigurer" > < property name="basePackage" value="com.mp.mapper"></property> </bean> </beans>Copy the code
The code structure of MP06 is as follows:
At this point, the extension demonstration based on Mybatis – Plus plug-in is completed, and now we can move on to the next section of the study of custom global operations and global SQL injection.
The source code
Mybatis -plus-in-action