mybatis pagehelper paging plugin uses

Anyone who has used mybatis knows that mybatis itself is small and simple. SQL is written in xml for unified management and optimization. Of course, there are also disadvantages. For example, in the process of using, we need to use paging. If we use the most primitive way, 1. Query the paging data, 2. Obtain the paging length, that is to say, we need to use two methods to complete the paging. Is there a better way of paging? The pagehelper paging plugin was born because of this. Its principle is to use the mybatis interceptor to intercept SQL when querying the database, and then modify it to achieve paging (if you really want to know the principle , mybatis interceptor, you will know what's going on after you learn it).


This blog first shows you how to use it, and then there is time to talk about his implementation principle.

1. Add maven dependencies

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.0</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2. Configure the interceptor plug-in in the Spring configuration file (it can also be configured in the xml of mybatis, not much to say here)

<!--配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="typeAliasesPackage" value="com.aoChine.model.entity" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />

        <!-- 配置mybatis分页插件PageHelper -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!-- 什么都不配,使用默认的配置 -->
                        <value></value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

3. Use

a) Interface for writing normal query statements 
write picture description here

interface: 
write picture description here

b) Call the interface at the service layer to implement paging. 
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325806152&siteId=291194637