JPA 分页查询是一种常用的数据库查询方式,它可以有效地减少查询时间,提高系统性能。JPA 分页查询的基本原理是将大量的数据分割成多个小块,然后逐个进行处理。
JPA 分页查询可以使用 Query 接口中的 setFirstResult() 和 setMaxResults() 方法来实现。setFirstResult() 方法用于设置从哪一条记录开始,setMaxResults() 方法用于设置最多返回多少条记录。例如:
Query query = entityManager.createQuery("SELECT e FROM Employee e"); query.setFirstResult(0); // 从第 0 条开始 query.setMaxResults(10); // 最多返回 10 条记录 List<Employee> list = query.getResultList(); // 返回列表
此外,JPA 还提供了一个 Pageable 类来实现分页功能。Pageable 类包含了 pageNumber、pageSize、sort 等属性,其中 pageNumber 表示要显示的页数,pageSize 表示要显示的记录数量,sort 表示要对哪些字段进行升序或者降序排序。例如:
Pageable pageable = PageRequest.of(0, 10, Sort.by("name").ascending()); // pageNumber=0, pageSize=10, sort=name asc Page<Employee> page = employeeRepository.findAll(pageable); // 返回分页对象
PersonDaoImpl在下面的部分显示如何逐页显示结果。
下面的代码来自Department.java。
package cn..common; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy="department") private Collection<Employee> employees; public Department() { employees = new ArrayList<Employee>(); } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setEmployees(Collection<Employee> employees) { this.employees = employees; } public int getId() { return id; } public String getName() { return name; } public Collection<Employee> getEmployees() { return employees; } public String toString() { return "Department no: " + getId() + ", name: " + getName(); } }
下面的代码来自PersonDaoImpl.java。
package cn..common; import java.util.Collection; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.transaction.annotation.Transactional; @Transactional public class PersonDaoImpl { public void test() { Employee emp = new Employee(); emp.setName("Tom"); emp.setSalary(123); emp.setStartDate(new Date()); emp.setId(1); Project pro = new Project(); pro.setName("Design"); pro.getEmployees().add(emp); Department dept = new Department(); dept.setName("Dept"); dept.getEmployees().add(emp); emp.setDepartment(dept); emp.getProjects().add(pro); em.persist(dept); em.persist(pro); em.persist(emp); } private String reportQueryName; private int currentPage; private int maxResults; private int pageSize; public int getPageSize() { return pageSize; } public int getMaxPages() { return maxResults / pageSize; } public void init(int pageSize, String countQueryName, String reportQueryName) { this.pageSize = pageSize; this.reportQueryName = reportQueryName; maxResults = ((Long) em.createNamedQuery(countQueryName) .getSingleResult()).intValue(); currentPage = 0; } public List getCurrentResults() { return em.createNamedQuery(reportQueryName) .setFirstResult(currentPage * pageSize) .setMaxResults(pageSize) .getResultList(); } public void next() { currentPage++; } public void previous() { currentPage--; if (currentPage < 0) { currentPage = 0; } } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } @PersistenceContext private EntityManager em; }
以下代码来自Project.java。
package cn..common; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Project { @Id protected int id; protected String name; @ManyToMany(mappedBy="projects") private Collection<Employee> employees; public Project() { employees = new ArrayList<Employee>(); } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setEmployees(Collection<Employee> employees) { this.employees = employees; } public int getId() { return id; } public String getName() { return name; } public Collection<Employee> getEmployees() { return employees; } public String toString() { return "Project id: " + getId() + ", name: " + getName(); } }
以下代码来自Employee.java。
package cn..common; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @NamedQueries({ @NamedQuery(name="findEmployeesAboveSal", query="SELECT e " + "FROM Employee e " + "WHERE e.department = :dept AND " + " e.salary > :sal"), @NamedQuery(name="findHighestPaidByDepartment", query="SELECT e " + "FROM Employee e " + "WHERE e.department = :dept AND " + " e.salary = (SELECT MAX(e2.salary) " + " FROM Employee e2 " + " WHERE e2.department = :dept)") }) public class Employee { @Id private int id; private String name; private long salary; @Temporal(TemporalType.DATE) private Date startDate; @ManyToOne private Employee manager; @OneToMany(mappedBy="manager") private Collection<Employee> directs; @ManyToOne private Department department; @ManyToMany private Collection<Project> projects; public Employee() { projects = new ArrayList<Project>(); directs = new ArrayList<Employee>(); } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSalary(long salary) { this.salary = salary; } public void setStartDate(Date startDate) { this.startDate = startDate; } public void setManager(Employee manager) { this.manager = manager; } public void setDirects(Collection<Employee> directs) { this.directs = directs; } public void setDepartment(Department department) { this.department = department; } public void setProjects(Collection<Project> projects) { this.projects = projects; } public int getId() { return id; } public String getName() { return name; } public long getSalary() { return salary; } public Date getStartDate() { return startDate; } public Department getDepartment() { return department; } public Collection<Employee> getDirects() { return directs; } public Employee getManager() { return manager; } public Collection<Project> getProjects() { return projects; } public String toString() { return "Employee " + getId() + ": name: " + getName() + ", salary: " + getSalary() + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); } }下载 Query_Paging.zip
上面的代码生成以下结果。
以下是数据库转储。
Table Name: DEPARTMENT Row: Column Name: ID, Column Type: INTEGER: Column Value: 0 Column Name: NAME, Column Type: VARCHAR: Column Value: Dept Table Name: EMPLOYEE Row: Column Name: ID, Column Type: INTEGER: Column Value: 1 Column Name: NAME, Column Type: VARCHAR: Column Value: Tom Column Name: SALARY, Column Type: BIGINT: Column Value: 123 Column Name: STARTDATE, Column Type: DATE: Column Value: 2014-12-29 Column Name: DEPARTMENT_ID, Column Type: INTEGER: Column Value: 0 Column Name: MANAGER_ID, Column Type: INTEGER: Column Value: null Table Name: EMPLOYEE_PROJECT Row: Column Name: EMPLOYEES_ID, Column Type: INTEGER: Column Value: 1 Column Name: PROJECTS_ID, Column Type: INTEGER: Column Value: 0 Table Name: PROJECT Row: Column Name: ID, Column Type: INTEGER: Column Value: 0 Column Name: NAME, Column Type: VARCHAR: Column Value: Design
Lucene教程 -Lucene搜索文件搜索过程是进行搜索的过程。下表列出了在搜索过程中使用的类。类描述IndexSearcher读取/搜索索引处理...
Java XML教程 -Java DOM编辑属性以下代码显示如何向元素添加属性。import java.io.StringWriter;import javax.xml.parsers.Docum...
Java线程教程 -Java线程优先级所有线程都有优先级。优先级由1到10之间的整数表示。优先级为1的线程优先级最低。优先级为10的线程...
JavaFX教程 -JavaFX滑块滑块可以显示和与一系列数值进行交互。滑块控件有两件事:一个轨道和一个可拖动的拇指。在轨道上,我们可...