CriteriaBuilder使用自定义条件连接两个表

时间:2016-04-04 15:09:36

标签: java jpa criteria-api

我想写这个SQL查询

SELECT *  
FROM A
LEFT OUTER JOIN B
ON A.IDRESOURCE=B.IDRESOURCE AND B.IDLANGUAGE=22;

使用JPA Criteria Builder。 我只用以下内容编写了连接的第一部分:

CriteriaQuery<A> searchQuery = criteriaBuilder.createQuery(A.class);
Root<A> aRoot = searchQuery.from(A.class);
Join<A, B> bJoin= aRoot.join("mappedB", JoinType.LEFT);

但我不知道如何实施条件B.IDLANGUAGE = 22。

有没有办法在Criteria Builder中实现这一目标?

2 个答案:

答案 0 :(得分:5)

Use JPA 2.1 ON to specify it in the JOIN part, which is not the same as in the WHERE

CriteriaQuery<A> searchQuery = criteriaBuilder.createQuery(A.class);
Root<A> aRoot = searchQuery.from(A.class);
Join<A, B> bJoin= aRoot.join("mappedB", JoinType.LEFT);
bJoin.on(criteriaBuilder.equal(bJoin.get("idLanguage"), 22));

答案 1 :(得分:-1)

使用whereCriteriaBuilder.equal

em.select(aRoot).where( criteriaBuilder.equal(bJoin.get("IdLanguage"), 22));