JPA/Criteria API - Like & equal problem
2022-08-31 19:48:43
我正在尝试在我的新项目中使用标准API:
public List<Employee> findEmps(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
c.select(emp);
c.distinct(emp);
List<Predicate> criteria = new ArrayList<Predicate>();
if (name != null) {
ParameterExpression<String> p = cb.parameter(String.class, "name");
criteria.add(cb.equal(emp.get("name"), p));
}
/* ... */
if (criteria.size() == 0) {
throw new RuntimeException("no criteria");
} else if (criteria.size() == 1) {
c.where(criteria.get(0));
} else {
c.where(cb.and(criteria.toArray(new Predicate[0])));
}
TypedQuery<Employee> q = em.createQuery(c);
if (name != null) {
q.setParameter("name", name);
}
/* ... */
return q.getResultList();
}
现在,当我更改此行时:
criteria.add(cb.equal(emp.get("name"), p));
自:
criteria.add(cb.like(emp.get("name"), p));
我收到一个错误,说:
CriteriaBuilder 类型中的方法 like(Expression, Expression) >不适用于参数(Path, ParameterExpression)
怎么了?