1

我正在尝试使用 JPA Criteria Builder 来连接两个表,Country并且Geotarget. 等效SQL的是

Select distinct Country.* from Country Inner Join Geotarget
 where 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, JoinType.INNER);
    Predicate predicate = criteriaBuilder.equal(Country_.id,Geotarget_.country);
    criteriaQuery = criteriaQuery.where(predicate);
    criteriaQuery.select(Country.class).distinct(true);
    return findAllObjects(criteriaQuery);

但这是错误的,它甚至没有在某些地方解析。特别是我似乎找不到连接行的代码,或者似乎不喜欢比较两个字段的等于原因。你能帮我吗,用正确的代码。

4

1 回答 1

1

我认为你不需要谓词。连接本身应该执行 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);
于 2013-01-15T14:21:16.590 回答