我正在尝试使用CONTAINS函数(MS SQL)创建Criteria API查询:
select*from com.t_person where where(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();
Run Code Online (Sandbox Code Playgroud)
但是获得异常:org.hibernate.hql.internal.ast.QuerySyntaxException:意外的AST节点:
有帮助吗?
您可以尝试使用 CriteriaBuilder之类的函数而不是该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(
//Like predicate
cb.like(
//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 likeCondition
cb.parameter(String.class, "likeCondition")));
TypedQuery<Person> tq = em.createQuery(query);
tq.setParameter("likeCondition", "%Doe%");
List<Person> people = tq.getResultList();
Run Code Online (Sandbox Code Playgroud)
这应该会产生类似于以下内容的查询:
select p from PERSON p where p.last_name like '%Doe%';
Run Code Online (Sandbox Code Playgroud)
如果你想坚持使用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();
Run Code Online (Sandbox Code Playgroud)
您的问题似乎缺少一些代码,所以我在这个代码片段中做了一些假设.