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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:56:10  来源:igfitidea点击:

Using JPA Criteria Builder with table joins

javahibernatejpa

提问by Dr BDO Adams

I'm trying to use the JPA Criteria Builder to join two tables, Countryand Geotarget. The equivalent SQLis

我正在尝试使用 JPA Criteria Builder 将两个表CountryGeotarget. 等价物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);