Mybatis-PageHelper的简单使用

Mybatis-PageHelper一个简洁易用的mybatis分页插件。java

文档地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.mdmysql

加入依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.4</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.41</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

如何使用

第一步:在mybatis-config.xml中配置插件git

<!--配置Mybatis-PageHelper插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>

第二步:使用它提供的APIgithub

PageHelper.startPage(1, 2);  //设置分页:显示第1页,每页显示2条
List<Emp> list = empMapper.findAll();
PageInfo<Emp> page = new PageInfo<Emp>(list);  //取得分页信息

进阶:加入MyBatis Generator(用法同样)

首先使用以下命令生成相应的代码spring

mvn mybatis-generator:generate

API的使用与上面同样sql

PageHelper.startPage(1, 2);  //设置分页:显示第一页,每页显示2条
List<Emp> list = empMapper.selectByExample(null);

整合Spring

只要在Spring的配置文件,加入此插件的配置便可。mybatis

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="plugins">
        <array>
            <!-- 配置Mybatis-PageHelper插件 -->
            <bean class="com.github.pagehelper.PageInterceptor"/>
        </array>
    </property>
</bean>

整合Spring Boot

加入依赖app

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.1.0</version>
</dependency>

在application.properties中配置(可选)spring-boot

#pagehelper.helper-dialect=mysql
相关文章
相关标签/搜索