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?
Let's see it step by step: Create an instance of Session from the SessionFactory object. Create an instance of CriteriaBuilder by calling the getCriteriaBuilder() method. Create an instance of CriteriaQuery by calling the CriteriaBuilder createQuery() method.
Following is Subquery interface snippet: package javax. persistence. criteria; .... public interface Subquery<T> extends AbstractQuery<T>, Expression<T> { Subquery<T> select(Expression<T> expression); Subquery<T> where(Expression<Boolean> restriction); Subquery<T> where(Predicate...
How can you select multiple fields using a criteria API query? 1: select * from STUDENT; 2: select ID, NAME from STUDENT; 3: select count(ID) from STUDENT; 4: SELECT s.NAME, a. /** create a Criteria Builder **/ CriteriaBuilder builder = em. CriteriaQuery<Long> cq = builder.
CriteriaQuery instance is used to create a query object. This query object's attributes will be modified with the details of the query. CriteriaQuery. from method is called to set the query root.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With