JPA(Java Persistence API)是Java EE和Java SE环境中处理持久化的API
示例:
String jpql = "SELECT e FROM Employee e WHERE e.department.name = :departmentName AND e.salary > :minSalary";
TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
query.setParameter("departmentName", "IT");
query.setParameter("minSalary", 5000);
List<Employee> employees = query.getResultList();
示例:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class);
Root<Employee> employeeRoot = criteriaQuery.from(Employee.class);
Join<Employee, Department> departmentJoin = employeeRoot.join("department");
Predicate departmentPredicate = criteriaBuilder.equal(departmentJoin.get("name"), "IT");
Predicate salaryPredicate = criteriaBuilder.greaterThan(employeeRoot.get("salary"), 5000);
criteriaQuery.where(criteriaBuilder.and(departmentPredicate, salaryPredicate));
TypedQuery<Employee> query = entityManager.createQuery(criteriaQuery);
List<Employee> employees = query.getResultList();
createNativeQuery()
方法创建一个原生SQL查询,然后使用unwrap()
方法将其转换为JPA查询。示例:
String sql = "SELECT * FROM employees e JOIN departments d ON e.department_id = d.id WHERE d.name = :departmentName AND e.salary > :minSalary";
TypedQuery<Employee> query = entityManager.createNativeQuery(sql, Employee.class);
query.setParameter("departmentName", "IT");
query.setParameter("minSalary", 5000);
List<Employee> employees = query.getResultList();
setFirstResult()
和setMaxResults()
方法进行分页,使用orderBy()
方法进行排序。示例:
String jpql = "SELECT e FROM Employee e WHERE e.department.name = :departmentName AND e.salary > :minSalary";
TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
query.setParameter("departmentName", "IT");
query.setParameter("minSalary", 5000);
query.setFirstResult(0); // 分页,从第0条记录开始
query.setMaxResults(10); // 分页,最多返回10条记录
query.orderBy(criteriaBuilder.asc(employeeRoot.get("salary"))); // 排序,按薪资升序排列
List<Employee> employees = query.getResultList();
subQuery()
方法创建一个子查询。示例:
String jpql = "SELECT e FROM Employee e WHERE e.salary > (SELECT AVG(e2.salary) FROM Employee e2 WHERE e2.department.name = :departmentName)";
TypedQuery<Employee> query = entityManager.createQuery(jpql, Employee.class);
query.setParameter("departmentName", "IT");
List<Employee> employees = query.getResultList();
通过掌握这些技巧,可以在JPA中实现复杂的查询。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。