pagehelper分页插件的简单实用
结合mybatis实现对pagehelper分页插件的简单使用。
一、创建一个maven项目并导入相关依赖
依赖文件:pom.xml
<?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"> <modelVersion>4.0.0</modelVersion> <groupId>com.mgy</groupId> <artifactId>Mybatis_10_pagehelper</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.13</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 分页插件的依赖 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> </dependencies> </project>
二、创建一个操作实体:Employee.java
package com.mgy.mybatis.bean; public class Employee { private Integer id; private String lastName; private String email; private String gender; private EmpStatus empStatus = EmpStatus.LOGOUT; public Employee() { } public Employee(String lastName, String email, String gender) { this.lastName = lastName; this.email = email; this.gender = gender; } public EmpStatus getEmpStatus() { return empStatus; } public void setEmpStatus(EmpStatus empStatus) { this.empStatus = empStatus; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", gender='" + gender + '\'' + '}'; } }
其他操作可能用到的枚举类:EmpStatus.java
package com.mgy.mybatis.bean; /** * @author MGY * @data 2019/11/20 22:00 */ public enum EmpStatus { LOGIN,LOGOUT,REMOVE; }
三、配置全局配置文件:mybatis-config.xml
<?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> <typeHandlers> <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.mgy.mybatis.bean.EmpStatus" /> </typeHandlers> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins> <environments default="dev_mysql"> <environment id="dev_mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?allowMultiQueries = true&useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> <environment id="dev_oracle"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" /> <property name="username" value="scott" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <!-- 5、databaseIdProvider: 支持多数据库厂商的 type="DB_VENDOR": VendorDatabaseIdProvider 作用就是得到数据库厂商的标识(驱动 getDatabaseProductName()) MySQL、Oracle、SQL Server ... --> <databaseIdProvider type="DB_VENDOR"> <!-- 为不同的数据库厂商起别名 --> <property name="MySQL" value="mysql"/> <property name="Oracle" value="oracle"/> <property name="SQL Server" value="sqlserver"/> </databaseIdProvider> <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 --> <mappers> <mapper resource="EmployeeMapper.xml" /> </mappers> </configuration>
四、配置一个日志配置文件,方便在控制台查看sql语句的操作:log4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <param name="Encoding" value="UTF-8" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="info" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration>
五、创建一个操作数据库的持久类:EmployeeMapper.java
package com.mgy.mybatis.dao; import com.mgy.mybatis.bean.Employee; import java.util.List; public interface EmployeeMapper { Employee getEmpById(Integer id); Long addEmps(Employee employee); List<Employee> getMySQLEmployees(); List<Employee> getOracleEmployees(); }
六、配置持久类EmployeeMapper.java的mybatis的映射文件:EmployeeMapper.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"> <!-- namespace: 名称空间;指定为接口的全类名 id: 唯一标识 resultType: 返回值类型 #{id}: 从传递过来的参数中取出 id 值 --> <mapper namespace="com.mgy.mybatis.dao.EmployeeMapper"> <select id="getEmpById" resultType="com.mgy.mybatis.bean.Employee" > select id, last_name lastName, email, gender from tbl_employee where id = #{id} </select> <!--Long addEmps(Employee employee);--> <insert id="addEmps" useGeneratedKeys="true" keyProperty="id"> insert into tbl_employee(last_name, email, gender, empStatus) values (#{lastName}, #{email}, #{gender}, #{empStatus}) </insert> <!-- List<Employee> getMySQLEmployees(); --> <select id="getMySQLEmployees" resultMap="PageEmp" databaseId="oracle"> select * from tbl_employee </select> <!-- List<Employee> getOracleEmployees(); --> <select id="getOracleEmployees" resultMap="PageEmp" databaseId="oracle"> select * from employees </select> <resultMap id="PageEmp" type="com.mgy.mybatis.bean.Employee"> <id column="employee_id" property="id" /> <result column="last_name" property="lastName" /> <result column="email" property="email" /> <result column="gender" property="gender" /> </resultMap> </mapper>
七、编写测试类:MyBatisTest.java
package com.mgy.mybatis.test; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.mgy.mybatis.bean.EmpStatus; import com.mgy.mybatis.bean.Employee; import com.mgy.mybatis.dao.EmployeeMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; /** * 1、接口式编程 * 原生: Dao ===========> DaoImpl * mybatis: Mapper ===========> xxMapper.xml * 2、SqlSession 代表和数据库的一次会话;用完必须关闭 * 3、SqlSession 和 connection 一样,它们都是非线程安全。每次使用都应该去获取新的对象 * 4、mapper 接口没有实现类,但是 mybatis 会为这个接口生成一个代理对象 * (将接口和 xml 进行绑定) * EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class); * 5、两个重要的配置文件: * mybatis 的全局配置文件:包含数据库连接池信息,事务处理器信息等....系统运行环境信息 * sql 映射文件:保存了每一个 sql 语句的映射信息: * 将 sql 抽取出来 */ public class MyBatisTest { public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } /** * 1、根据 xml 配置文件(全局配置文件)创建一个 SqlSessionFactory 对象 有数据源一些运行环境信息 * 2、sql 映射文件;配置了每一个 sql,以及 sql 的封装规则等。 * 3、将 sql 映射文件注册在全局配置文件中 * 4、写代码: * 1)、根据全局配置文件得到 SqlSessionFactory * 2)、使用 sqlSessionFactory 获取到 sqlSession 对象,使用它来执行增删改查 * 一个 sqlSession 就是代表和数据库的一次会话,用完关闭 * 3)、使用 sql 的唯一标识来告诉 MyBatis 执行哪个 sql。sql 都是保存在 sql 映射文件中的 * @throws IOException */ @Test public void test() throws IOException { // 2、获取sqlSession实例,能直接执行已经映射的sql语句 SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); try { // selectOne 的参数 // 参数1 sql的唯一标识:statement Unique identifier matching the statement to use. // 参数2 执行sql要用的参数:parameter A parameter object to pass to the statement. Employee employee = sqlSession.selectOne("com.mgy.mybatis.dao.EmployeeMapper.getEmpById", 1); System.out.println(employee); } finally { sqlSession.close(); } } @Test public void test01() throws IOException { // 1、获取 sqlSessionFactory 对象 SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); // 2、获取 sqlSession 对象 SqlSession sqlSession = sqlSessionFactory.openSession(); try { // 3、获取接口的实现类对象 // MyBatis 会为接口自动的创建一个代理对象,代理对象去执行增删改查方法 EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee empById = mapper.getEmpById(1); System.out.println(mapper.getClass()); System.out.println(empById); } finally { sqlSession.close(); } } @Test public void testBatch() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); // 可以执行批量操作的 sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); long start = System.currentTimeMillis(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); for (int i = 0; i < 10000; i++) { mapper.addEmps(new Employee(UUID.randomUUID().toString().substring(0, 5), "b", "1")); } sqlSession.commit(); long end = System.currentTimeMillis(); /* * 批量:(预编译 sql 一次 ==> 设置参数 10000 次 ===> 执行一次) 执行时长:12394 * Parameters: 09c31(String), b(String), 1(String) (BaseJdbcLogger.java:145) * * 非批量: (预编译 sql = 设置参数 = 执行 = 10000 次) 执行时长:21923 * Preparing: insert into tbl_employee(last_name, email, gender) values (?, ?, ?) (BaseJdbcLogger.java:145) * Parameters: 48154(String), b(String), 1(String) (BaseJdbcLogger.java:145) * */ System.out.println("执行时长:"+ (end - start)); } finally { sqlSession.close(); } } /** * MySQL 的测试 * @throws IOException */ @Test public void testMySQLPageHelper() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Page<Object> page = PageHelper.startPage(1, 5); List<Employee> employees = mapper.getMySQLEmployees(); for (Employee employee : employees) { System.out.println(employee); } System.out.println("当前页码:"+page.getPageNum()); System.out.println("总记录数:"+page.getTotal()); System.out.println("每页的记录数:"+page.getPageSize()); System.out.println("总页码:"+page.getPages()); // 传入要连续显示多少页 PageInfo<Employee> info = new PageInfo<Employee>(employees, 5); for (Employee employee : employees) { System.out.println(employee); } ///xxx System.out.println("当前页码:"+info.getPageNum()); System.out.println("总记录数:"+info.getTotal()); System.out.println("每页的记录数:"+info.getPageSize()); System.out.println("总页码:"+info.getPages()); System.out.println("是否第一页:"+info.isIsFirstPage()); System.out.println("连续显示的页码:"); int[] nums = info.getNavigatepageNums(); for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } } finally { sqlSession.close(); } } /** * Oracle 测试 * @throws IOException */ @Test public void testOraclePageHelper() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Page<Object> page = PageHelper.startPage(1, 5); List<Employee> employees = mapper.getOracleEmployees(); for (Employee employee : employees) { System.out.println(employee); } System.out.println("当前页码:"+page.getPageNum()); System.out.println("总记录数:"+page.getTotal()); System.out.println("每页的记录数:"+page.getPageSize()); System.out.println("总页码:"+page.getPages()); // 传入要连续显示多少页 PageInfo<Employee> info = new PageInfo<Employee>(employees, 5); for (Employee employee : employees) { System.out.println(employee); } ///xxx System.out.println("当前页码:"+info.getPageNum()); System.out.println("总记录数:"+info.getTotal()); System.out.println("每页的记录数:"+info.getPageSize()); System.out.println("总页码:"+info.getPages()); System.out.println("是否第一页:"+info.isIsFirstPage()); System.out.println("连续显示的页码:"); int[] nums = info.getNavigatepageNums(); for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } } finally { sqlSession.close(); } } @Test public void testEnumUse() { EmpStatus login = EmpStatus.LOGIN; System.out.println("枚举的索引:"+login.ordinal()); System.out.println("枚举的名字:"+login.name()); } /** * 默认 mybatis 在处理枚举对象的时候保存的是枚举的名字: EnumTypeHandler * 改变使用:EnumOrdinalTypeHandler * @throws IOException */ @Test public void testEnum() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee("test_enum", "enum@qq.com", "1"); mapper.addEmps(employee); System.out.println("保存成功:"+employee.getId()); sqlSession.commit(); } finally { sqlSession.close(); } } }