Java JPA/Criteria API - Like & equal 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4014390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA/Criteria API - Like & equal problem
提问by John Manak
I'm trying to use Criteria API in my new project:
我正在尝试在我的新项目中使用 Criteria 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();
}
Now when I change this line:
现在当我改变这一行时:
criteria.add(cb.equal(emp.get("name"), p));
to:
到:
criteria.add(cb.like(emp.get("name"), p));
I get an error saying:
我收到一条错误消息:
The method like(Expression, Expression) in the type CriteriaBuilder is not > applicable for the arguments (Path, ParameterExpression)
CriteriaBuilder 类型中的 like(Expression, Expression) 方法不适用于参数 (Path, ParameterExpression)
What's the problem?
有什么问题?
采纳答案by axtavt
Perhaps you need
也许你需要
criteria.add(cb.like(emp.<String>get("name"), p));
because first argument of like()
is Expression<String>
, not Expression<?>
as in equal()
.
因为第一个参数的like()
就是Expression<String>
,不Expression<?>
作为equal()
。
Another approach is to enable generation of the static metamodel (see docs of your JPA implementation) and use typesafe Criteria API:
另一种方法是启用静态元模型的生成(请参阅 JPA 实现的文档)并使用类型安全的 Criteria API:
criteria.add(cb.like(emp.get(Employee_.name), p));
(Note that you can't get static metamodel from em.getMetamodel()
, you need to generate it by external tools).
(请注意,您无法从 中获取静态元模型em.getMetamodel()
,您需要通过外部工具生成它)。
回答by user3077341
Better: predicate (not ParameterExpression
), like this :
更好:谓词(不是ParameterExpression
),像这样:
List<Predicate> predicates = new ArrayList<Predicate>();
if(reference!=null){
Predicate condition = builder.like(root.<String>get("reference"),"%"+reference+"%");
predicates.add(condition);
}
回答by Abdessamad HALLAL
Use :
用 :
personCriteriaQuery.where(criteriaBuilder.like(
criteriaBuilder.upper(personRoot.get(Person_.description)),
"%"+filter.getDescription().toUpperCase()+"%"));