紧接着上文,写个分页查询。
普通方式
1.1 接口StudentMapper
接口StudentMapper增加分页方法listByPage:
package ymqx.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import ymqx.entities.Student;
import java.util.List;
public interface StudentMapper {
/**
* 根据学生编号获得学生对象
*/
@Select("select id,name,sex from student where id=#{id}")
Student selectStudentByIdAnno(int id);
@Select("select * from student limit #{start},#{count}")
List<Student> listByPage(@Param("start") int start, @Param("count")int count);
}
start:是指从第0个开始,如果是第二页,那么start = count * (2-1) = 5。
count:是指每页有5条数据。
1.2 数据访问类
StudentDao:
package ymqx.dao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import ymqx.entities.Student;
import ymqx.mapper.StudentMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class StudentDao implements StudentMapper {
@Override
public Student selectStudentByIdAnno(int id){
Student student = mapper.selectStudentByIdAnno(id);
return student;
}
@Override
public List<Student> listByPage(int start, int count) {
List<Student> students = mapper.listByPage(start, count);
return students;
}
StudentMapper mapper;
{
//使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
String resource = "conf.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
//构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建能执行映射文件中sql的sqlSession
SqlSession session=sqlSessionFactory.openSession();
mapper = session.getMapper(StudentMapper.class);
}
public static void main(String[] args) {
StudentDao dao=new StudentDao();
List<Student> students = dao.listByPage(0, 5);
for (Student s :students ) {
System.out.println(s);
}
}
}
输出:
Student{id=1001, name=‘lili’, sex=‘girl’}
Student{id=1002, name=‘shwen’, sex=‘boy’}
Student{id=1003, name=‘jack’, sex=‘secret’}
Student{id=1004, name=‘colu’, sex=‘secret’}
Student{id=1005, name=‘sala’, sex=‘secret’}
PageHelper
PageHelper 是一款犀利的Mybatis分页插件,使用了这个插件之后,分页开发起来更加简单容易。
2.1 添加依赖
【pagehelper】
com.github.pagehelper-5.1.2.jar
【jsqlparser】
com.github.jsqlparser-1.0.jar
2.2 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>ymqx</groupId>
<artifactId>MyBatis01</artifactId>
<version>1.0-SNAPSHOT</version>
<name>MyBatis01</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!--MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--MySql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- JUnit单元测试工具 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- Jpagehelper分页 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>
2.3 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>
<!-- 别名 使得在后续配置文件studentMapper.xml中使用resultType的时候,可以直接使用Student,而不必写全mqx.entities.Student-->
<typeAliases>
<package name="ymqx.entities"/>
</typeAliases>
<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/how2java"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper resource="mapper/studentMapper.xml"/> -->
<mapper class="ymqx.mapper.StudentMapper"></mapper>
</mappers>
</configuration>
表示开启PageHelper插件。
2.4 接口StudentMapper去除limit
因为分页相关工作,会由PageHelper去做,不需要自己去写了。
package ymqx.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import ymqx.entities.Student;
import java.util.List;
public interface StudentMapper {
/**
* 根据学生编号获得学生对象
*/
@Select("select id,name,sex from student where id=#{id}")
Student selectStudentByIdAnno(int id);
@Select("select * from student")
List<Student> listByPage(int start, int count);
}
2.5 数据访问类
只需要在执行查询所有的调用之前,执行一条语句即可:
PageHelper.offsetPage(0, 5);
StudentDao:
public class StudentDao implements StudentMapper {
@Override
public Student selectStudentByIdAnno(int id){
Student student = mapper.selectStudentByIdAnno(id);
return student;
}
@Override
public List<Student> listByPage(int start, int count) {
PageHelper.offsetPage(start, count);
List<Student> students = mapper.listByPage(start, count);
return students;
}
StudentMapper mapper;
{
//使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
String resource = "conf.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
//构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建能执行映射文件中sql的sqlSession
SqlSession session=sqlSessionFactory.openSession();
mapper = session.getMapper(StudentMapper.class);
}
public static void main(String[] args) {
StudentDao dao=new StudentDao();
List<Student> students = dao.listByPage(0,5);
for (Student s :students ) {
System.out.println(s);
}
}
}
运行结果:
Student{id=1001, name=‘lili’, sex=‘girl’}
Student{id=1002, name=‘shwen’, sex=‘boy’}
Student{id=1003, name=‘jack’, sex=‘secret’}
Student{id=1004, name=‘colu’, sex=‘secret’}
Student{id=1005, name=‘sala’, sex=‘secret’}
2.6 获取记录总数
只需要在执行查询结果,再执行下面方法,获取分页信息,包括总数以及其他的
PageInfo pageInfo = new PageInfo<>(students);
StudentDao:
public class StudentDao implements StudentMapper {
...
public static void main(String[] args) {
StudentDao dao=new StudentDao();
List<Student> students = dao.listByPage(0,5);
for (Student s :students ) {
System.out.println(s);
}
PageInfo pageInfo = new PageInfo<>(students);
System.out.println("当前总数:" + pageInfo.getSize() + " 总数:"+pageInfo.getTotal());
System.out.println(pageInfo);
}
}
Student{id=1001, name=‘lili’, sex=‘girl’}
Student{id=1002, name=‘shwen’, sex=‘boy’}
Student{id=1003, name=‘jack’, sex=‘secret’}
Student{id=1004, name=‘colu’, sex=‘secret’}
Student{id=1005, name=‘sala’, sex=‘secret’}
当前总数:5 总数:8
PageInfo{pageNum=1, pageSize=5, size=5, startRow=1, endRow=5, total=8, pages=2, list=Page{count=true, pageNum=1, pageSize=5, startRow=0, endRow=5, total=8, pages=2, reasonable=false, pageSizeZero=false}, prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=8, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}