Condition left join in CriteriaQuery

Ricardo Romero Benítez picture Ricardo Romero Benítez · Nov 13, 2014 · Viewed 20.8k times · Source

Hi everybody I am trying to do this in CriteriaQuery, I was searching so long but I can't found anything to do it, someone can help me?

SELECT b.name
FROM Empl a 
LEFT OUTER JOIN Deplo b ON (a.id_depl = b.id_depl) AND b.id_place = 2;

I'm just trying to do a condition in left join clause, I saw ".on" function but I don't know if it will work and how it work because I tried to do something like this:

Join Table1, Table2j1 = root.join(Table1_.table2, JoinType.LEFT).on(cb.and(cb.equal(table2_.someid, someId)));

But it need a boolean expresion.

Answer

wypieprz picture wypieprz · Nov 14, 2014

The on clause has been introduced in JPA 2.1. An example solution:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<String> cq = cb.createQuery(String.class);
    Root<Empl> a = cq.from(Empl.class);
    Join<Empl,Deplo> b = a.join("b", JoinType.LEFT); //left outer join
    b.on(
        cb.and(
            cb.equal(b.get("id_place"), cb.parameter(Integer.class, "idPlace")),
            cb.equal(b.get("id_depl"), a.get("id_depl"))
        )   
    );
    cq.select(b.<String>get("name"));

    List<String> results = em.createQuery(cq)
                             .setParameter("idPlace", 2)
                             .getResultList();