本篇文章小编给大家分享一下Mybatis利用分页插件PageHelper快速实现分页查询代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
首先创建一个Maven项目
导入相关依赖:
mysql mysql-connector-java 8.0.25 junit junit 4.13 test com.github.pagehelper pagehelper 5.2.1 org.mybatis mybatis 3.5.7 log4j log4j 1.2.17
记住导入PageHelper依赖:
com.github.pagehelper pagehelper 5.2.1
数据库中创建一张表
设置Mybatis配置文件
在resources目录下,创建一个sqlMapConfig.xml文件,用于做一些全局的mybatis基本的配置,例如数据库连接信息,事务,mapper映射文件路径,日志实现,类的别名,也包含了分页插件的基本配置。
编写pojo实体类和mapper接口和mapper映射文件
Student实体类
package pojo; public class Student { private Integer id; private String name; private String email; private Integer age; public Student() { } public Student(Integer id, String name, String email, Integer age) { this.id = id; this.name = name; this.email = email; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + ''' + ", email='" + email + ''' + ", age=" + age + '}'; } }
mapper接口
package mapper; import pojo.Student; import java.util.List; public interface StudentMapper { //查询所有学生 ListselectAll(); }
Mapper映射文件
在sqlMapConfig文件中指定Mapper文件位置
编写MyBatisUtils
package utils; 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 java.io.IOException; import java.io.InputStream; /** * 工具类:创建SqlSession对象 */ public class MyBatisUtil { private static SqlSessionFactory factory = null; static { String config="sqlMapConfig.xml"; try { InputStream inputStream =Resources.getResourceAsStream(config); factory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //创建方法,获取SqlSession对象 public static SqlSession getSqlSession(){ SqlSession session = null; if( factory != null ){ session =factory.openSession();// openSession(true); } return session; } }
创建测试类
import com.github.pagehelper.PageHelper; import mapper.StudentMapper; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import pojo.Student; import utils.MyBatisUtil; import java.util.List; public class pageHelper_Test { @Test public void PageHelperTest(){ //获取sqlSession SqlSession sqlSession = MyBatisUtil.getSqlSession(); //获取mapper代理 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); //调用PageHelper PageHelper.startPage(2,2); //查询所有学生 ListstudentList = mapper.selectAll(); //遍历结果List集合 studentList.forEach(student -> System.out.println(student)); //关闭sqlSession对象 sqlSession.close(); } }
查看结果
可以看到sql语句,在mapper文件中并没有写limit,pageHelper已经帮我们加上了limit关键字完成了查询.