📅  最后修改于: 2023-12-03 15:16:40.997000             🧑  作者: Mango
JPA(Java Persistence API)是Java的一个ORM(对象关系映射)规范。JPQL(Java Persistence Query Language)是JPA中定义的用于查询Java持久化对象的语言。
JPQL可以操作JPA中的Entity,它类似于SQL语言,但是并不是针对数据库的查询语言,而是针对对象关系的查询语言。使用JPQL,我们可以从数据库中获取实体,并根据需要进行过滤和排序。
JPQL的语法和SQL类似,但也有一些不同之处。
查询所有实体示例:
SELECT e FROM Employee e
SELECT e FROM Employee e
在这个例子中,查询的实体是Employee,"e"是Employee类的别名,"SELECT"关键字声明了返回类型为Employee的实体。
过滤查询示例:
SELECT e FROM Employee e WHERE e.department.name='Development'
SELECT e FROM Employee e WHERE e.department.name='Development'
在这个例子中,我们通过"Department"类来过滤Employee实体,"WHERE"子句提供了过滤条件。
排序查询结果示例:
SELECT e FROM Employee e ORDER BY e.salary DESC
SELECT e FROM Employee e ORDER BY e.salary DESC
在这个例子中,我们可以根据查询结果中的"salary"字段进行排序。DESC关键字指定了降序排列。
分页查询示例:
SELECT e FROM Employee e ORDER BY e.salary DESC
SELECT e FROM Employee e ORDER BY e.salary DESC
在这个例子中,我们可以使用"setFirstResult"和"setMaxResults"方法来对查询结果进行分页。
以下示例展示了如何在Java中使用JPQL。
创建一个Employee实体类:
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private double salary;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "DEPARTMENT_ID")
private Department department;
// getter / setters ...
}
创建一个Department实体类:
@Entity
@Table(name = "DEPARTMENT")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY)
private Set<Employee> employees = new HashSet<>();
// getter / setters ...
}
List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e", Employee.class).getResultList();
List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e", Employee.class).getResultList();
List<Department> departments = entityManager.createQuery("SELECT d FROM Department d", Department.class).getResultList();
List<Department> departments = entityManager.createQuery("SELECT d FROM Department d", Department.class).getResultList();
List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e ORDER BY e.salary DESC", Employee.class).getResultList();
List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e ORDER BY e.salary DESC", Employee.class).getResultList();
List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e WHERE e.department.name='Development'", Employee.class).getResultList();
List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e WHERE e.department.name='Development'", Employee.class).getResultList();
JPQL提供了一个强大的标准化查询语言,我们可以使用它来完成JPA中的各种查询操作,包括过滤、排序和分页。JPA-JPQL可能需要一些学习成本,但它是一个强大的工具,可以帮助我们更高效、更灵活地工作。