使用Criteria Builder运行带有IN子句的查询

时间:2019-06-12 16:29:07

标签: java hibernate hibernate-criteria

我需要使用CriteriaBuilder方法来运行以下查询的帮助:

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))

1 个答案:

答案 0 :(得分:1)

类似这样的事情。由于缺少实体名称,我无法给您查询。但是,我建议阅读此Criteria API subselect

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