Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition left join in CriteriaQuery

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.

like image 680
Ricardo Romero Benítez Avatar asked Nov 13 '14 09:11

Ricardo Romero Benítez


1 Answers

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();
like image 99
wypieprz Avatar answered Oct 19 '22 21:10

wypieprz