Condition left join in CriteriaQuery

落爺英雄遲暮 提交于 2019-12-22 05:37:11

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/26905047/condition-left-join-in-criteriaquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!