JPA - CriteriaQuery with "WHERE" clause

11,298

Solution 1

Parameters are set in Criteria queries the same as in JPQL or native queries, you set them on 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 one pass the name to parameter().

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

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

Solution 2

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

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

...

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

Provided you have Metamodel classes built. See also Chapter 40 of the Java EE Tutorial.

Regards, Thomas

Share:
11,298

Related videos on Youtube

Joe Almore
Author by

Joe Almore

Updated on June 20, 2022

Comments

  • Joe Almore
    Joe Almore almost 2 years

    I know this can be a very simple question to some of u, but I'm having a hard time trying to find out how to build a simple Select * From X Where X.a = :myparam using a CriteriaBuilder.

    Now, this is the code I have managed to build 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 where I am applying this query is this one:

    @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 records from myclass1 "WHERE" anotherClass.id = 1L, and where do I set the "1L", I know it goes in p but where?

    That's all. Looks simple, but I am really not familiar with this CriteriaBuilder thing, so hope you can have some answers.

    Thanks.