我需要一些帮助来运行下面的查询,使用 CriteriaBuilder aproach:
select count(*) from TABLE_VIEW_SEARCH where
person_ID in (select person_ID from TABLE_PERSON
where region_ID = 1001) and postal_cd ='AL';
我试过这个,但它失败了:
CriteriaBuilder cb = ..;
CriteriaQuery<Long> criteriaQuery= cb.createQuery(Long.class);
Root<ViewSearchEntity> from= criteriaQuery.from(ViewSearchEntity.class);
Subquery<Long> subQuery = criteriaQuery.subquery(Long.class);
Root<PersonEntity> subFrom = subQuery .from(PersonEntity.class);
subQuery .where(cb.equal(subFrom.get(PersonEntity_.region_ID ), region_ID ));
criteriaQuery.select(cb.count(from));
criteriaQuery.where(meFrom.in(subQuery );
TypedQuery<Long> query = getEntityManager().createQuery(criteriaQuery);
Long result = query.getSingleResult();
我达成了一个解决方案,基本上我设法做到了连接条件:
CriteriaBuilder cb = ..;
CriteriaQuery<Long> criteriaQuery= cb.createQuery(Long.class);
Root<ViewSearchEntity> from= criteriaQuery.from(ViewSearchEntity.class);
Predicate predicate1 = cb.equal(from.get(ViewSearchEntity.postal_cd),"AL");
Subquery<Long> subQuery = criteriaQuery.subquery(Long.class);
Root<PersonEntity> subRoot = subQuery.from(PersonEntity.class);
Join<PersonEntity, RegionEntity_> region= subRoot.join(RegionEntity_.region);
subQuery.select(region.get(RegionEntity_.regionId)).where(
cb.equal(subRoot.get(PersonEntity_.region), regionId));
Predicate predicateInClause = root.get(ViewSearchEntity_.postal_cd).in(subQuery);
return getEntityManager().createQuery(criteriaQuery.select(cb.count(root)).where(predicate1,predicateInClause)).getEntityManager().createQuery(criteriaQuery.select(cb.count(root)).where(predicate1,predicateInClause))
像这样的东西。由于缺少实体名称,我无法给您查询。但是,我建议阅读此标准 API 子选择
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(TABLE_VIEW_SEARCH.class);
Root root = cq.from(TABLE_VIEW_SEARCH.class);
Subquery sub = cq.subquery(TABLE_PERSON.class);
Root subRoot = sub.from(TABLE_PERSON.class);
SetJoin<TABLE_PERSON, TABLE_VIEW_SEARCH> subViewSearch =
subRoot.join(TABLE_PERSON.tableViewSearch);
sub.select(cb.equal(subRoot.get(TABLE_PERSON.region_ID), 1001));
cq.where(cb.equal(root.get("postal_cd"), "AL"));
TypedQuery query = em.createQuery(cq);
List result = query.getResultList();
声明元模型生成依赖项后,可以使用此方法:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
添加此依赖项后,使用 maven 重新生成项目,然后可以执行以下操作:
EntityName_.attribute