java CriteriaBuilder 用自定义条件连接两个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36406390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CriteriaBuilder join two tables with a custom condition
提问by gvdm
I want to write this SQL query
我想写这个 SQL 查询
SELECT *
FROM A
LEFT OUTER JOIN B
ON A.IDRESOURCE=B.IDRESOURCE AND B.IDLANGUAGE=22;
with the JPA Criteria Builder. I wrote the first part of the join simply with:
使用 JPA 标准生成器。我简单地写了连接的第一部分:
CriteriaQuery<A> searchQuery = criteriaBuilder.createQuery(A.class);
Root<A> aRoot = searchQuery.from(A.class);
Join<A, B> bJoin= aRoot.join("mappedB", JoinType.LEFT);
but I don't know how to implement the condition B.IDLANGUAGE=22.
但我不知道如何实现条件 B.IDLANGUAGE=22。
Is there any way to accomplish this in Criteria Builder?
有什么方法可以在 Criteria Builder 中完成此操作吗?
回答by Neil Stockton
Use JPA 2.1 ON
to specify it in the JOIN
part, which is notthe same as in the WHERE
使用JPA 2.1ON
在指定它JOIN
的一部分,这是不一样的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));
回答by K.Nicholas
Use where
and CriteriaBuilder.equal
.
使用where
和CriteriaBuilder.equal
。
em.select(aRoot).where( criteriaBuilder.equal(bJoin.get("IdLanguage"), 22));