在JPA中,可以使用以下幾種方式解決query參數問題:
String queryString = "SELECT e FROM Employee e WHERE e.salary > :salary";
TypedQuery<Employee> query = entityManager.createQuery(queryString, Employee.class);
query.setParameter("salary", 50000);
List<Employee> employees = query.getResultList();
String queryString = "SELECT e FROM Employee e WHERE e.salary > ?1";
TypedQuery<Employee> query = entityManager.createQuery(queryString, Employee.class);
query.setParameter(1, 50000);
List<Employee> employees = query.getResultList();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Employee> root = cq.from(Employee.class);
cq.select(root).where(cb.gt(root.get("salary"), 50000));
TypedQuery<Employee> query = entityManager.createQuery(cq);
List<Employee> employees = query.getResultList();
無論使用哪種方式,都可以解決JPA中的query參數問題,選擇最適合自己情況的方式即可。