您好,登錄后才能下訂單哦!
JPA(Java Persistence API)是Java EE和Java SE環(huán)境中處理持久化的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()
方法創(chuàng)建一個(gè)原生SQL查詢,然后使用unwrap()
方法將其轉(zhuǎn)換為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();
setMaxResults()
方法進(jìn)行分頁(yè),使用orderBy()
方法進(jìn)行排序。示例:
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); // 分頁(yè),從第0條記錄開(kāi)始
query.setMaxResults(10); // 分頁(yè),最多返回10條記錄
query.orderBy(criteriaBuilder.asc(employeeRoot.get("salary"))); // 排序,按薪資升序排列
List<Employee> employees = query.getResultList();
subQuery()
方法創(chuàng)建一個(gè)子查詢。示例:
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();
通過(guò)掌握這些技巧,可以在JPA中實(shí)現(xiàn)復(fù)雜的查詢。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。