SpringBoot2 實(shí)現(xiàn)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: # 更新或者創(chuàng)建數(shù)據(jù)表結(jié)構(gòu) ddl-auto: update # 控制臺顯示SQL show-sql: true properties: hibernate.format_sql: true
實(shí)體類
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer empId;
private String lastName;
private String email;
@Temporal(TemporalType.DATE)
private Date birth;
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@ManyToOne
@JoinColumn(name = "dept_id")
private Department department;
// 省去 set get方法
}
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer deptId;
private String deptName;
// 省去 set get方法
}
Repository接口類
import com.springboot.jpa.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}
service 接口類
import com.springboot.jpa.entity.Employee;
import org.springframework.data.domain.Page;
public interface EmployeeService {
// 普通分頁
Page<Employee> getPage(Integer pageNum, Integer pageLimit);
// 排序分頁
Page<Employee> getPageSort(Integer pageNum, Integer pageLimit);
}
Service 實(shí)現(xiàn)類
import com.springboot.jpa.dao.EmployeeRepository;
import com.springboot.jpa.entity.Employee;
import com.springboot.jpa.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
// 普通分頁
@Override
@Transactional(readOnly = true) // 只讀事務(wù)
public Page<Employee> getPage(Integer pageNum, Integer pageLimit) {
Pageable pageable =new PageRequest(pageNum - 1,pageLimit);
return employeeRepository.findAll(pageable);
}
// 分頁排序
@Override
@Transactional(readOnly = true)
public Page<Employee> getPageSort(Integer pageNum, Integer pageLimit) {
Sort sort = new Sort(Sort.Direction.DESC,"createTime");
Pageable pageable =new PageRequest(pageNum - 1, pageLimit, sort);
return employeeRepository.findAll(pageable);
}
}
Controller控制器類
import com.springboot.jpa.entity.Employee;
import com.springboot.jpa.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
// 分頁顯示數(shù)據(jù)
@GetMapping("/emp")
public Page<Employee> showPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "size") Integer size){
System.out.println("分頁: page:"+page+"; size:"+size);
return employeeService.getPage(page, size);
}
// 排序分頁顯示數(shù)據(jù)
@GetMapping("/emp_sort")
public Page<Employee> showSortPage(@RequestParam(value = "page") Integer page, @RequestParam(value = "size") Integer size){
System.out.println("排序分頁: page:"+page+"; size:"+size);
return employeeService.getPageSort(page, size);
}
}
分頁顯示的json格式串
http://localhost:8080/emp_sort?page=1&size=10 url格式
{
"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
}
補(bǔ)充:Spring Data Jpa普通分頁+排序分頁
SpringBoot2 使用jpa分頁問題
一、 jap的普通分頁:
pojo
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String userName;
@Column
private String password;
@Column
private String age;
//省略get、set
}
IUserService
//jpa簡單分頁 Page<User> getPage(Integer pageNum,Integer pageSize);
UserService
@Override
public Page<User> getPage(Integer pageNum, Integer pageSize) {
/**
*之前看到別的博主直接new PageRequest(pageNum-1,pageSize)
*自己實(shí)踐后報(bào)錯(cuò),可能是因?yàn)榘姹静灰恢掳?
*查看PageRequest的底層構(gòu)造方法并沒有對應(yīng)的只有of方法對應(yīng)
*后經(jīng)實(shí)驗(yàn)成功!
*/
//創(chuàng)建一個(gè)pageable,調(diào)用它的實(shí)現(xiàn)類PageRequest的of()方法
Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
Page<User> userPage = userDao.findAll(pageable);
return userPage;
}
Test
@Test
void testGetPage(){
//調(diào)用service層的getPage()方法
Page<User> userPage = userService.getPage(1, 5);
/**
* userPage.getContent()
* getContent(); 獲取查詢的結(jié)果集
* Page<Object>常用方法
* List<T> getContent(); 將所有數(shù)據(jù)返回為List
* long getTotalElements();返回元素總數(shù)
* int getTotalPages(); 返回分頁總數(shù)
*/
List<User> users = userPage.getContent();
for (User user : users) {
System.out.println(user);
}
}
結(jié)果:
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
public Page<User> getPage(Integer pageNum, Integer pageSize) {
//普通查詢跟排序查詢的唯一區(qū)別在于Sort
//排序方式,這里的by()方法跟上面的那個(gè)of()方法作用差不多
//Sort.Direction.DESC: 倒序
//Sort.Direction.ASC :默認(rèn)升序
//Sort.by(Sort.Direction.***, "實(shí)體類中的字段");
//根據(jù)實(shí)體類中的字段進(jìn)行排序(我使用的"age")
Sort sort = Sort.by(Sort.Direction.DESC, "age");
//創(chuàng)建一個(gè)pageable,調(diào)用它的實(shí)現(xiàn)類PageRequest的of()方法
//將sort加入到of()中排序完成
Pageable pageable = PageRequest.of(pageNum - 1, pageSize,sort);
Page<User> userPage = userDao.findAll(pageable);
return userPage;
}
Test
省略單元測試
結(jié)果:
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}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
SpringBoot整合JavaMail通過阿里云企業(yè)郵箱發(fā)送郵件的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot整合JavaMail通過阿里云企業(yè)郵箱發(fā)送郵件的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
SpringBoot利用MDC機(jī)制過濾單次請求的所有日志
在服務(wù)出現(xiàn)故障時(shí),我們經(jīng)常需要獲取一次請求流程里的所有日志進(jìn)行定位 ,如何將一次數(shù)據(jù)上報(bào)請求中包含的所有業(yè)務(wù)日志快速過濾出來,就是本文要介紹的,需要的朋友可以參考下2024-04-04
SpringBoot詳解如何整合Redis緩存驗(yàn)證碼
本文主要介紹了SpringBoot集成Redis實(shí)現(xiàn)驗(yàn)證碼的緩存簡單案例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07
淺談springboot內(nèi)置tomcat和外部獨(dú)立部署tomcat的區(qū)別
這篇文章主要介紹了淺談springboot內(nèi)置tomcat和外部獨(dú)立部署tomcat的區(qū)別,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
淺析Java中JNI靜態(tài)注冊和動(dòng)態(tài)注冊
這篇文章主要為大家詳細(xì)介紹了Java中JNI靜態(tài)注冊和動(dòng)態(tài)注冊的相關(guān)知識,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12
Java如何導(dǎo)入Jsoup庫做一個(gè)有趣的爬蟲項(xiàng)目
Jsoup庫是一款Java的HTML解析器,可用于從網(wǎng)絡(luò)或本地文件中獲取HTML文檔并解析其中的數(shù)據(jù),這篇文章給大家介紹Java導(dǎo)入Jsoup庫做一個(gè)有趣的爬蟲項(xiàng)目,感興趣的朋友跟隨小編一起看看吧2023-11-11

