mybatis · 2019-09-16 0

mybatis使用pagehelper插件

1.maven依赖

添加pagehelper依赖

<dependencies>

    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <!--mysql-connector-java-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

    <!--slf4j门面-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>

    <!--slf4j-simple-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.25</version>
    </dependency>

    <!--pagehelper-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.10</version>
    </dependency>

    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

</dependencies>

2.mybatis配置

在类路径下新建mybatis-config.xml

在mybatis配置文件中,配置分页插件

<?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>

    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>

    <!--分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--<mappers>
        包扫描,dao接口名与sql映射文件名相同,且放在同一包下
        <package name="com.example.dao"/>
    </mappers>-->

    <mappers>
        <mapper resource="mapper/studentDao.xml"/>
    </mappers>

</configuration>

3.日志文件配置

在类路径下新建 simplelogger.properties 文件

org.slf4j.simpleLogger.defaultLogLevel=debug

4.JavaBean

public class Student {

    private int id;

    private String name;

    private int age;

    // get、set、toString() 方法
}

5.Dao与Mapping

StudentDao.java

public interface StudentDao {

    /**
     * 获取
     */
    List<Student> selectList();

}

studentDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.StudentDao">

    <select id="selectList" resultType="com.example.bean.Student">
        SELECT
            *
        FROM student
    </select>

</mapper>

6.测试

public class MyBatisTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void before() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testSelect() {
        SqlSession openSession = null;
        try{
            openSession = sqlSessionFactory.openSession();
            StudentDao studentDao = openSession.getMapper(StudentDao.class);

            // 紧跟他的查询就是一个分页查询
            PageHelper.startPage(2, 3);
            List<Student> list = studentDao.selectList();

            // 将查询的结果放在pageinfo中,这个pageInfo就有非常多功能
            PageInfo<Student> info = new PageInfo<>(list);
            System.out.println("当前页码:" + info.getPageNum());
            System.out.println("总页码:" + info.getPages());
            System.out.println("总记录数:" + info.getTotal());
            System.out.println("当前页有几条记录:" + info.getSize());
            System.out.println("当前页的pageSize:" + info.getPageSize());
            System.out.println("前一页:" + info.getPrePage());
            System.out.println("结果:" + info.getList());

            for (Student student : list){
                System.out.println(student);
            }
        }finally {
            openSession.close();
        }
    }

}

结果:

[main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
[main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 926434463.
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 926434463 to pool.
[main] DEBUG SQL_CACHE - Cache Hit Ratio [SQL_CACHE]: 0.0
[main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Checked out connection 926434463 from pool.
[main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3738449f]
[main] DEBUG com.example.dao.StudentDao.selectList_COUNT - ==>  Preparing: SELECT count(0) FROM student 
[main] DEBUG com.example.dao.StudentDao.selectList_COUNT - ==> Parameters: 
[main] DEBUG com.example.dao.StudentDao.selectList_COUNT - <==      Total: 1
[main] DEBUG com.example.dao.StudentDao.selectList - ==>  Preparing: SELECT * FROM student LIMIT ?, ? 
[main] DEBUG com.example.dao.StudentDao.selectList - ==> Parameters: 3(Integer), 3(Integer)
[main] DEBUG com.example.dao.StudentDao.selectList - <==      Total: 3
当前页码:2
总页码:5
总记录数:14
当前页有几条记录:3
当前页的pageSize:3
前一页:1
结果:Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=14, pages=5, reasonable=false, pageSizeZero=false}[Student{id=4, name='name4', age=4}, Student{id=5, name='name5', age=5}, Student{id=6, name='name6', age=6}]
Student{id=4, name='name4', age=4}
Student{id=5, name='name5', age=5}
[main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3738449f]
Student{id=6, name='name6', age=6}
[main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3738449f]
[main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 926434463 to pool.