您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。