Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to crete Criteria API query with CONTAINS function(MS SQL):

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();

But getting exception: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node:

Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
495 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to stick with using CONTAINS, it should be something like this:

//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();

It seems like some of your code is missing from your question so I'm making a few assumptions in this snippet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...