java 将 JPA Criteria Builder 与表连接一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14339401/
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
Using JPA Criteria Builder with table joins
提问by Dr BDO Adams
I'm trying to use the JPA Criteria Builder to join two tables, Country
and Geotarget
.
The equivalent SQL
is
我正在尝试使用 JPA Criteria Builder 将两个表Country
和Geotarget
. 等价物SQL
是
Select distinct Country.* from Country Inner Join Geotarget
where Geotarget.Country_ID = Country.ID;
my code is
我的代码是
CriteriaBuilder criteriaBuilder getTransactionalEntityManager().getCriteriaBuilder();
CriteriaQuery<Country> criteriaQuery = criteriaBuilder.createQuery(Country.class);
Root<Country> root = criteriaQuery.from(Country.class);
Join<Geotarget, Country> geotargetJoin = root.join(Geotarget_.country, JoinType.INNER);
Predicate predicate = criteriaBuilder.equal(Country_.id,Geotarget_.country);
criteriaQuery = criteriaQuery.where(predicate);
criteriaQuery.select(Country.class).distinct(true);
return findAllObjects(criteriaQuery);
But is wrong, it doesn't even parse in places. In particular i can't seem to find the code for either the join line, or the equals cause which doesn't seem to like to compare two fields. Can you help me, with the correct code.
但错了,它甚至没有在某些地方解析。特别是我似乎无法找到连接线或似乎不喜欢比较两个字段的 equals 原因的代码。你能帮我,用正确的代码。
回答by Καrτhικ
I don't think you need the predicate. The join itself should perform the GeoTarget.Country_ID = Country.ID. So revise to:
我认为你不需要谓词。联接本身应执行 GeoTarget.Country_ID = Country.ID。所以修改为:
CriteriaBuilder criteriaBuilder getTransactionalEntityManager().getCriteriaBuilder();
CriteriaQuery<Country> criteriaQuery = criteriaBuilder.createQuery(Country.class);
Root<Country> root = criteriaQuery.from(Country.class);
Join<Geotarget, Country> geotargetJoin = root.join(Geotarget_.country); // Default is inner
criteriaQuery.select(Country.class).distinct(true);
return findAllObjects(criteriaQuery);