具有CONTAINS功能的JPA Criteria API

我正在尝试使用CONTAINS函数(MS SQL)创建Criteria API查询:

从com.t_person中选择*,其中包含(last_name,’xxx’)

CriteriaBuilder cb = em.getCriteriaBuilder();

CriteriaQuery<Person> cq = cb.createQuery(Person.class);

Root<Person> root = cq.from(Person.class);

Expression<Boolean> function = cb.function("CONTAINS", Boolean.class,

root.<String>get("lastName"),cb.parameter(String.class, "containsCondition"));

cq.where(function);

TypedQuery<Person> query = em.createQuery(cq);

query.setParameter("containsCondition", lastName);

return query.getResultList();

但是出现异常:org.hibernate.hql.internal.ast.QuerySyntaxException:意外的AST节点:

有什么帮助吗?

回答:

如果您要坚持使用CONTAINS,则应该是这样的:

//Get criteria builder

CriteriaBuilder cb = em.getCriteriaBuilder();

//Create the CriteriaQuery for Person object

CriteriaQuery<Person> query = cb.createQuery(Person.class);

//From clause

Root<Person> personRoot = query.from(Person.class);

//Where clause

query.where(

cb.function(

"CONTAINS", Boolean.class,

//assuming 'lastName' is the property on the Person Java object that is mapped to the last_name column on the Person table.

personRoot.<String>get("lastName"),

//Add a named parameter called containsCondition

cb.parameter(String.class, "containsCondition")));

TypedQuery<Person> tq = em.createQuery(query);

tq.setParameter("containsCondition", "%näh%");

List<Person> people = tq.getResultList();

您的问题似乎缺少一些代码,因此在此代码段中我做了一些假设。

以上是 具有CONTAINS功能的JPA Criteria API 的全部内容, 来源链接: utcz.com/qa/418261.html

回到顶部