SpringBoot2 实现JPA分页和排序分页的案例
分页
application.yml
spring: datasource: url:jdbc:mysql://127.0.0.1/jpa?useUnicode=true&characterEncoding=utf-8&useSSL=false username:root password:123456 driver-class-name:com.mysql.jdbc.Driver jpa: hibernate: #更新或者创建数据表结构 ddl-auto:update #控制台显示SQL show-sql:true properties: hibernate.format_sql:true
实体类
@Entity @Table(name="employee") publicclassEmployee{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) privateIntegerempId; privateStringlastName; privateStringemail; @Temporal(TemporalType.DATE) privateDatebirth; @Temporal(TemporalType.TIMESTAMP) privateDatecreateTime; @ManyToOne @JoinColumn(name="dept_id") privateDepartmentdepartment; //省去setget方法 } @Entity @Table(name="department") publicclassDepartment{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) privateIntegerdeptId; privateStringdeptName; //省去setget方法 }
Repository接口类
importcom.springboot.jpa.entity.Employee; importorg.springframework.data.jpa.repository.JpaRepository; publicinterfaceEmployeeRepositoryextendsJpaRepository{ }
service接口类
importcom.springboot.jpa.entity.Employee; importorg.springframework.data.domain.Page; publicinterfaceEmployeeService{ //普通分页 PagegetPage(IntegerpageNum,IntegerpageLimit); //排序分页 Page getPageSort(IntegerpageNum,IntegerpageLimit); }
Service实现类
importcom.springboot.jpa.dao.EmployeeRepository; importcom.springboot.jpa.entity.Employee; importcom.springboot.jpa.service.EmployeeService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.domain.Page; importorg.springframework.data.domain.PageRequest; importorg.springframework.data.domain.Pageable; importorg.springframework.data.domain.Sort; importorg.springframework.stereotype.Service; importorg.springframework.transaction.annotation.Transactional; @Service publicclassEmployeeServiceImplimplementsEmployeeService{ @Autowired privateEmployeeRepositoryemployeeRepository; //普通分页 @Override @Transactional(readOnly=true)//只读事务 publicPagegetPage(IntegerpageNum,IntegerpageLimit){ Pageablepageable=newPageRequest(pageNum-1,pageLimit); returnemployeeRepository.findAll(pageable); } //分页排序 @Override @Transactional(readOnly=true) publicPage getPageSort(IntegerpageNum,IntegerpageLimit){ Sortsort=newSort(Sort.Direction.DESC,"createTime"); Pageablepageable=newPageRequest(pageNum-1,pageLimit,sort); returnemployeeRepository.findAll(pageable); } }
Controller控制器类
importcom.springboot.jpa.entity.Employee; importcom.springboot.jpa.service.EmployeeService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.domain.Page; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.RestController; @RestController publicclassEmployeeController{ @Autowired privateEmployeeServiceemployeeService; //分页显示数据 @GetMapping("/emp") publicPageshowPage(@RequestParam(value="page")Integerpage,@RequestParam(value="size")Integersize){ System.out.println("分页:page:"+page+";size:"+size); returnemployeeService.getPage(page,size); } //排序分页显示数据 @GetMapping("/emp_sort") publicPage showSortPage(@RequestParam(value="page")Integerpage,@RequestParam(value="size")Integersize){ System.out.println("排序分页:page:"+page+";size:"+size); returnemployeeService.getPageSort(page,size); } }
分页显示的json格式串
http://localhost:8080/emp_sort?page=1&size=10url格式
{ "content":[{ "lastName":"7QW", "email":"453@qq.com", "birth":"2018-08-06", "createTime":"2018-08-30T07:40:34.000+0000", "id":5, "dempartment":{ "deptName":"BBB", "id":2 } },{ "lastName":"qax", "email":"1223@qq.com", "birth":"2018-08-06", "createTime":"2018-08-24T07:40:56.000+0000", "id":6, "dempartment":{ "deptName":"AAA", "id":1 } } }], "pageable":{ "sort":{ "sorted":true, "unsorted":false }, "offset":0, "pageNumber":0, "pageSize":10, "unpaged":false, "paged":true }, "last":true, "totalElements":6, "totalPages":1, "number":0, "size":10, "sort":{ "sorted":true, "unsorted":false }, "numberOfElements":6, "first":true }
补充:SpringDataJpa普通分页+排序分页
SpringBoot2使用jpa分页问题
一、jap的普通分页:
pojo
@Entity @Table(name="user") publicclassUser{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) privateIntegerid; @Column privateStringuserName; @Column privateStringpassword; @Column privateStringage; //省略get、set }
IUserService
//jpa简单分页 PagegetPage(IntegerpageNum,IntegerpageSize);
UserService
@Override publicPagegetPage(IntegerpageNum,IntegerpageSize){ /** *之前看到别的博主直接newPageRequest(pageNum-1,pageSize) *自己实践后报错,可能是因为版本不一致吧 *查看PageRequest的底层构造方法并没有对应的只有of方法对应 *后经实验成功! */ //创建一个pageable,调用它的实现类PageRequest的of()方法 Pageablepageable=PageRequest.of(pageNum-1,pageSize); Page userPage=userDao.findAll(pageable); returnuserPage; }
Test
@Test voidtestGetPage(){ //调用service层的getPage()方法 PageuserPage=userService.getPage(1,5); /** *userPage.getContent() *getContent();获取查询的结果集 *Page
结果:
User{id=17,userName=‘大锤',password=‘1***3',age=23} User{id=18,userName=‘小黑',password=‘w***w',age=21} User{id=19,userName=‘小白',password=‘2***1',age=29} User{id=20,userName=‘小红',password=‘4***2',age=19} User{id=21,userName=‘小芳',password=‘2***3',age=17}
二、jap的普通分页:
IUserService
同上
UserService
@Override publicPagegetPage(IntegerpageNum,IntegerpageSize){ //普通查询跟排序查询的唯一区别在于Sort //排序方式,这里的by()方法跟上面的那个of()方法作用差不多 //Sort.Direction.DESC:倒序 //Sort.Direction.ASC:默认升序 //Sort.by(Sort.Direction.***,"实体类中的字段"); //根据实体类中的字段进行排序(我使用的"age") Sortsort=Sort.by(Sort.Direction.DESC,"age"); //创建一个pageable,调用它的实现类PageRequest的of()方法 //将sort加入到of()中排序完成 Pageablepageable=PageRequest.of(pageNum-1,pageSize,sort); Page userPage=userDao.findAll(pageable); returnuserPage; }
Test
省略单元测试
结果:
User{id=19,name=‘小白',password=‘2***1',age=29} User{id=16,name=‘老李',password=‘8***7',age=25} User{id=17,name=‘大锤',password=‘1***3',age=23} User{id=15,name=‘老宋',password=‘9***0',age=22} User{id=18,name=‘小黑',password=‘w***w',age=21}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。