Mybatis Reverse Engineering & paging plug-in

1. Paging plug-in

MjBatis provides a plug-in mechanism so that we can enhance the function of MyBats according to our own needs. It should be noted that if you do not fully understand the operation principle of lMy Batis and the working mode of plug-ins, you'd better not use plug-ins, because it will change the working logic at the bottom of the system and have a great impact on the system.
MyBatis plug-in can change the behavior of the four core objects by intercepting without modifying the original code, such as processing parameters, processing SQL and processing results.

Typical application scenarios of Mybatis plug-in

Paging function

By default, the paging of mybatis is based on memory paging (find out all and then intercept). It is inefficient when there is a large amount of data. However, this behavior can be changed by using mybatis plug-in. You only need to intercept the prepare method of StatementHandler class and change the SQL statement to be executed into paging statement;

plug-in unit

MyBatis allows you to intercept calls at some point during the execution of mapping statements. By default, MyBatis allows the use of plug-ins to intercept method calls, including:

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)
    The details of the methods in these classes can be found by viewing the signature of each method, or directly viewing the source code in the MyBatis distribution package. If you want to do more than just monitor method calls, you'd better have a good understanding of the behavior of the method to be rewritten. Because when trying to modify or rewrite the behavior of existing methods, it is likely to destroy the core module of MyBatis. These are lower level classes and methods, so be careful when using plug-ins.
    Through the powerful mechanism provided by MyBatis, using the plug-in is very simple. You only need to implement the Interceptor interface and specify the method signature you want to intercept.
// ExamplePlugin.java
@Intercepts({@Signature(
  type= Executor.class,
  method = "update",
  args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
  private Properties properties = new Properties();
  public Object intercept(Invocation invocation) throws Throwable {
    // Pretreatment if necessary
    Object returnObject = invocation.proceed();
    // Post processing if necessary
    return returnObject;
  }
  public void setProperties(Properties properties) {
    this.properties = properties;
  }
}
<!-- mybatis-config.xml -->
<plugins>
  <plugin interceptor="org.mybatis.example.ExamplePlugin">
    <property name="someProperty" value="100"/>
  </plugin>
</plugins>

The above plug-in will intercept all "update" method calls in the Executor instance, where the Executor is the internal object responsible for executing the underlying mapping statement.
Prompt override configuration class
In addition to using plug-ins to modify the core behavior of MyBatis, you can also achieve this by completely overriding the configuration class. Just inherit the configuration class, override one of the methods, and then pass it to sqlsessionfactorybuilder Build (myconfig) method. Again, this may greatly affect MyBatis's behavior. Please be careful.

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.0</version><!--Latest version-->
</dependency>

2. Configure interceptor plug-in

In particular, the new interceptor is com github. pagehelper . PageInterceptor. com.grithub.pagehelper .PageHelper is now a special dialect implementation class. It is the default implementation class of paging plug-in and provides the same usage as before.

1. Configure interceptor plug-in in MyBatis configuration xml

<!--plugins The position in the configuration file must meet the requirements, otherwise an error will be reported, in the following order:
properties?, settings ?,
typeAliases? , typeHandlers ? ,
objectFactory? ,objectwrapperFactory? ,plugins?,
environments?, databaseIdProvider? , mappers?
-->
<plugins>
	<!-- com.github.pagehelper by PageHelper Package name of class-->
	<plugin interceptor="com.github.pagehelper.PageInterceptor">
		<!-- Use the following method to configure parameters. All parameters will be described later-->
		<property name="param1" value="value1"/>
	</plugin>
</plugins>

2. Configure the interceptor plug-in in the Spring configuration file

Using the spring property configuration method, you can use the plugins property to configure as follows:

<!--plug-in unit:It can be understood as mybatis The interceptor can intercept 4 large objects and can intercept SQL to SQL Add some public functions-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- Note other configurations -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!--Configure parameters in the following way, one per line -->
          <value>
            params=value1
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>

3. Introduction to paging plug-in parameters

The paging plug-in provides several optional parameters. When these parameters are used, they can be configured according to the examples in the above two configuration methods.
The optional parameters of the paging plug-in are as follows:

  • Dialect: PageHelper mode will be used for paging by default. If you want to implement your own paging logic, you can implement the Dialect(com.github.pagehelper.Dialect) interface, and then configure this attribute as the fully qualified name of the implementation class
    The following parameters are for the default dialog. When using a custom dialect implementation, the following parameters have no effect.
  1. helperDialect: the paging plug-in will automatically detect the current database link and automatically select the appropriate paging method. You can configure the helperDialect property to specify which dialect the paging plug-in uses. When configuring, you can use the following abbreviations:
    oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby
    **Special note: * * when using sqlserver2012 database, you need to manually specify it as sqlserver2012, otherwise you will use SqlServer2005 for paging.
    You can also implement AbstractHelperDialect, and then configure the property to the fully qualified name of the implementation class to use the custom implementation method.
  2. offsetAsPageNum: the default value is false. This parameter is valid when RowBounds is used as the paging parameter. When this parameter is set to true, the offset parameter in RowBounds will be used as pageNum, which can be paged with page number and page size.
  3. rowBoundsWithCount: the default value is false. This parameter is valid when rowboundaries is used as the paging parameter. When this parameter is set to true, count query will be performed using RowBounds paging.
  4. Pagesizezzero: the default value is false. When this parameter is set to true, if pageSize=0 or owboundaries If limit = 0, all the results will be queried (equivalent to that the paged query is not executed, but the returned result is still of Page type).
  5. reasonable: paging rationalization parameter. The default value is false. When this parameter is set to true, the first page will be queried when pagenum < = 0, and the last page will be queried when pagenum > pages (exceeds the total). When the default is false, the query is performed directly according to the parameters.
  6. Params: in order to support the startPage(Object params) method, this parameter is added to configure the parameter mapping. It is used to take values from the object according to the attribute name. pageNum,pageSize,count,pageSizeZero,reasonable can be configured. If the mapping is not configured, the default value is pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero.
  7. supportMethodsArguments: supports the transfer of paging parameters through Mapper interface parameters. The default value is false. The paging plug-in will automatically take values from the parameter values of the query method according to the fields configured in params above. When an appropriate value is found, it will automatically page. For the usage method, please refer to com.com in the test code github. pagehelper. test. ArgumentsMapTest and ArgumentsObjTest under the basic package.
  8. autoRuntimeDialect: the default value is false. When set to true, it is allowed to automatically identify the paging of the corresponding dialect according to multiple data sources at runtime (automatic selection of sqlserver2012 is not supported, only sqlserver can be used). Refer to scenario 5 below for usage and precautions.
  9. closeConn: the default value is true. When the runtime dynamic data source is used or the helperDialect property is not set to automatically obtain the database type, a database connection will be automatically obtained. This property is used to set whether to close the obtained connection. It is closed by default. When it is set to false, the obtained connection will not be closed. The setting of this parameter should be determined according to the data source you choose.
  10. aggregateFunctions(5.1.5 +): it is the aggregate function of all common databases by default. It is allowed to add aggregate functions (affecting the number of rows) manually. All functions starting with aggregate functions will set a layer during count conversion. Other functions and columns will be replaced with count(0), where the count column can be configured by itself.

Important:

When offsetAsPageNum=false, due to the PageNum problem, reasonable will be forced to be false during RowBounds query. Use PageHelper The startpage method is not affected.

3. How to use in code

//The first is the call of RowBounds mode
List<User> list = sqlSession.selectList("x.y.selectIf", null, new RowBounds(0, 10));

//Second, the Mapper interface mode is recommended.
PageHelper.startPage(1, 10);
List<User> list = userMapper.selectIf(1);

//The third way is to call Mapper interface mode, which is recommended.
PageHelper.offsetPage(1, 10);
List<User> list = userMapper.selectIf(1);

//Fourth, parameter method call
//There are the following Mapper interface methods. You don't need two parameters after xml processing
public interface CountryMapper {
    List<User> selectByPageNumSize(
            @Param("user") User user,
            @Param("pageNum") int pageNum, 
            @Param("pageSize") int pageSize);
}
//Configure supportMethodsArguments=true
//Call directly in Code:
List<User> list = userMapper.selectByPageNumSize(user, 1, 10);

//Fifth, parameter object
//If pageNum and pageSize exist in the User object, they will also be paged as long as the parameter has a value
//There are the following User objects
public class User {
    //Other fields
    //The following two parameter names are consistent with the names of params configuration
    private Integer pageNum;
    private Integer pageSize;
}
//There are the following Mapper interface methods. You don't need two parameters after xml processing
public interface CountryMapper {
    List<User> selectByPageNumSize(User user);
}
//When pagenum in user= null && pageSize!=  When null, automatic paging occurs
List<User> list = userMapper.selectByPageNumSize(user);

//Sixth, ISelect interface mode
//jdk6,7 usage, creating interface
Page<User> page = PageHelper.startPage(1, 10).doSelectPage(new ISelect() {
    @Override
    public void doSelect() {
        userMapper.selectGroupBy();
    }
});
//jdk8 lambda usage
Page<User> page = PageHelper.startPage(1, 10).doSelectPage(()-> userMapper.selectGroupBy());

//You can also return PageInfo directly. Pay attention to the doSelectPageInfo method and doSelectPage
pageInfo = PageHelper.startPage(1, 10).doSelectPageInfo(new ISelect() {
    @Override
    public void doSelect() {
        userMapper.selectGroupBy();
    }
});
//Corresponding lambda usage
pageInfo = PageHelper.startPage(1, 10).doSelectPageInfo(() -> userMapper.selectGroupBy());

//Count query returns the count of a query statement
long total = PageHelper.count(new ISelect() {
    @Override
    public void doSelect() {
        userMapper.selectLike(user);
    }
});
//lambda
total = PageHelper.count(()->userMapper.selectLike(user));

Keywords: Java Database Mybatis

Added by ben2.0 on Sat, 05 Feb 2022 12:33:27 +0200