7

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

select * from com.t_person where contains(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 节点:

有什么帮助吗?

4

2 回答 2

7

如果你想坚持使用 using 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();

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

于 2013-08-30T13:38:11.153 回答
5

您可以尝试使用 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();

这应该会产生类似于以下内容的查询:

select p from PERSON p where p.last_name like '%Doe%';
于 2013-08-28T13:37:54.060 回答