hibernatejpajoinhibernate-criteria

how to do a JOIN FETCH in jpa criteria


I am trying to translate the query below to criteria api.

SELECT er from ereturn er JOIN FETCH product_item pi ON pi.ereturn_id = er.id WHERE pi.status = "RECEIVED"

To something like this:

CriteriaBuilder builder = em.getCriteriaBuilder();

CriteriaQuery<Ereturn> criteria = builder.createQuery( Ereturn.class );

Root<Ereturn> er = criteria.from(Ereturn.class);
Join<Ereturn, ProductItem> productItemJoin = er.join("productItems", JoinType.LEFT);
Fetch<Ereturn, ProductItem> productItemFetch = er.fetch("productItems", JoinType.LEFT);

List<Predicate> predicates = new ArrayList<>();

predicates.add(builder.equal( productItemJoin.get( "status" ), "RECEIVED"));

criteria.where(
        builder.and(predicates.toArray(new Predicate[predicates.size()]))
);

List<Ereturn> ers = em.createQuery( criteria )
    .getResultList();

The problem is that hibernate generates this query:

select
ereturn0_.id as ...
...
productite6_.id as ...
...
from
ereturn ereturn0_ 
join
product_item productite1_ 
on ereturn0_.id = productite1_.ereturn 
join
product_item productite6_ 
on ereturn0_.id = productite6_.ereturn
where
productite1_.status='RECEIVED';

QUESTION: how could I tell hibernate to generate this query with only 1 join while fetching fields from both tables (ereturn and productItem)?


Solution

  • Indeed that is an issue, but your answer shows two additional tables and isn't the correct answer. Try this:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Ereturn> q = cb.createQuery(Ereturn.class);
    Root<Ereturn> r = q.from(Ereturn.class);
    r.fetch("productItem", JoinType.LEFT);
    // here join with the root instead of the fetch
    // casting the fetch to the join could cause portability problems
    // plus, not nice
    q.where(cb.equal(r.get("productItem").get("status"), "received"));
    Ereturn ereturn= em.createQuery(q).getSingleResult();
    

    which gives

    select ereturn0_.id as id1_0_0_, productite1_.id as id1_1_1_, ereturn0_.parentEreturn_id as parentCo2_0_0_, ereturn0_.productItem_id as productI3_0_0_, productite1_.status as status2_1_1_ 
    from Ereturn ereturn0_ 
    left outer join ProductItem productite1_ on ereturn0_.productItem_id=productite1_.id 
    where productite1_.status=?
    

    See JPA 2 Criteria Fetch Path Navigation a little further down in the answers.