JPA - CriteriaQuery with WHERE clause

I know this may be a very simple question for some of and, but I'm having difficulty trying to figure out how to build a simple Select * From X, where Xa =: MyParam using CriteriaBuilder.

Now this is the code that I have managed to create so far:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(); Root<MyClass1> r = cq.from(MyClass1.class); cq.select(r); ParameterExpression<Long> p = cb.parameter(Long.class); cq.where(cb.equal(r.get("anotherClass.id"), p)); javax.persistence.Query q = getEntityManager().createQuery(cq); 

The class in which I apply this query is as follows:

 @Entity public class MyClass1 implements Serializable { @Id private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ANOTHERCLASS_ID") private AnotherClass anotherClass; ... } @Entity public class AnotherClass implements Serializable { @Id private Long id; ... } 

I just need to select all the entries from MyClass1 "WHERE" anotherClass.id = 1L , and where can I set to "1L", I know this goes to p , but where?

It's all. It looks simple, but I'm really not familiar with this CriteriaBuilder thing, so I hope you can have the answers.

Thanks.

+4
source share
2 answers

The parameters are set the same in Criteria queries, as in JPQL or your own queries, you set them in the query.

i.e.

 javax.persistence.Query q = getEntityManager().createQuery(cq); q.setParameter(1, 1L); 

Note that you are using a positional parameter, to use a named parameter, pass the name to the parameter ().

 ParameterExpression<Long> p = cb.parameter(Long.class, "id"); ... q.setParameter("id", 1L); 

See, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Parameters

+3
source

you are trying to use a joined table in a where clause expression, so you need to use the join between tghe tables first.

  ...
 Join <MyClass1, ANotherClass> pathA = r.join (MyClass.anotherClass);

 ...

 cb.where (cb.equal (pathA.get (AnotherClass_.id), p));

If you have Metamodel classes. See also chapter 40 of the Java EE tutorial.

Regards, Thomas

+1
source

Source: https://habr.com/ru/post/1382791/


All Articles