我正在尝试使用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);
但是错了,它甚至没有在某些地方解析。特别是我似乎无法找到连接线的代码,或者似乎不喜欢比较两个字段的等于原因。 你能用正确的代码帮助我吗?
答案 0 :(得分: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);