javax.persistence.criteria.Subquery类的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(14.8k)|赞(0)|评价(0)|浏览(248)

本文整理了Java中javax.persistence.criteria.Subquery类的一些代码示例,展示了Subquery类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Subquery类的具体详情如下:
包路径:javax.persistence.criteria.Subquery
类名称:Subquery

Subquery介绍

[英]The Subquery interface defines functionality that is specific to subqueries. A subquery has an expression as its selection item.
[中]Subquery接口定义了特定于子查询的功能。子查询有一个表达式作为其选择项。

代码示例

代码示例来源:origin: kiegroup/jbpm

public <R> Predicate createPredicate(QueryCriteria criteria, CriteriaQuery<R> query, CriteriaBuilder builder) {
  // subquery and root
  Root<TaskImpl> taskRoot = getRoot(query, TaskImpl.class);
  Subquery<Long> subQuery = query.subquery(Long.class);
  Root<TaskVariableImpl> taskVarRoot = subQuery.from(TaskVariableImpl.class);
  subQuery.select(taskVarRoot.get(TaskVariableImpl_.taskId));
  // task variable predicate (in subquery)
  Predicate taskVariablePredicate = null;
  String listId = criteria.getListId();
  if( TASK_VARIABLE_COMBINED_ID.equals(listId) ) {
    List<QueryCriteria> taskVarSubCriteriaList = criteria.getCriteria();
    int size = taskVarSubCriteriaList.size();
    Predicate[] taskVarSubPredicates = new Predicate[size];
    for( int i = 0; i < size; ++i ) {
      taskVarSubPredicates[i] = createSingleTaskVariableCriteriaPredicate(
          builder, taskVarRoot, taskVarSubCriteriaList.get(i));
    }
    taskVariablePredicate = builder.and(taskVarSubPredicates);
  } else {
    taskVariablePredicate = createSingleTaskVariableCriteriaPredicate(builder, taskVarRoot, criteria);
  }
  // add predicate to subquery
  subQuery.where(taskVariablePredicate);
  // create predicate for actual query that references subquery
  return taskRoot.get(TaskImpl_.id).in(subQuery);
}

代码示例来源:origin: hibernate/hibernate-orm

@Override
@SuppressWarnings({ "unchecked" })
public <Y> Expression<Y> all(Subquery<Y> subquery) {
  return new SubqueryComparisonModifierExpression<Y>(
      this,
      (Class<Y>) subquery.getJavaType(),
      subquery,
      SubqueryComparisonModifierExpression.Modifier.ALL
  );
}

代码示例来源:origin: kiegroup/jbpm

if( LAST_VARIABLE_LIST.equals(criteria.getListId()) ) {
  Subquery<VariableInstanceLog> maxIdSubQuery = query.subquery(VariableInstanceLog.class);
  Root from = maxIdSubQuery.from(VariableInstanceLog.class);
  maxIdSubQuery.select(builder.max(from.get(VariableInstanceLog_.id)));
  maxIdSubQuery.groupBy(
      from.get(VariableInstanceLog_.variableId), 
      from.get(VariableInstanceLog_.processInstanceId));

代码示例来源:origin: org.jboss.pressgang.ccms/pressgang-ccms-query

protected Subquery<Integer> getLatestCompleteRevisionSubquery() {
  final CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
  final Subquery<Integer> subQuery = getCriteriaQuery().subquery(Integer.class);
  final Root<TranslatedTopicData> root = subQuery.from(TranslatedTopicData.class);
  subQuery.select(criteriaBuilder.max(root.get("translatedTopic").get("topicRevision").as(Integer.class)));
  final Predicate topicIdMatch = criteriaBuilder.equal(root.get("translatedTopic").get("topicId"), translatedTopic.get("topicId"));
  final Predicate localeMatch = criteriaBuilder.equal(getOriginalRootPath().get("translationLocale"), root.get("translationLocale"));
  final Predicate complete = criteriaBuilder.ge(root.get("translationPercentage").as(Integer.class), 100);
  subQuery.where(criteriaBuilder.and(topicIdMatch, localeMatch, complete));
  subQuery.groupBy(root.get("translatedTopic").get("topicId"));
  return subQuery;
}

代码示例来源:origin: Jasig/uPortal

@Override
  public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
    final CriteriaQuery<DateDimensionImpl> criteriaQuery =
        cb.createQuery(DateDimensionImpl.class);
    final Root<DateDimensionImpl> dimensionRoot =
        criteriaQuery.from(DateDimensionImpl.class);
    // Build subquery for max date
    final Subquery<LocalDate> maxDateSub =
        criteriaQuery.subquery(LocalDate.class);
    final Root<DateDimensionImpl> maxDateDimensionSub =
        maxDateSub.from(DateDimensionImpl.class);
    maxDateSub.select(
        cb.greatest(
            maxDateDimensionSub.get(DateDimensionImpl_.date)));
    // Get the date dimension
    criteriaQuery
        .select(dimensionRoot)
        .where(
            cb.equal(
                dimensionRoot.get(DateDimensionImpl_.date),
                maxDateSub));
    return criteriaQuery;
  }
});

代码示例来源:origin: com.moodysalem.java/jaxrs-lib

public static <T extends BaseEntity> Subquery<T> subquery(
    final CriteriaBuilder cb,
    final Class<T> clazz,
    final Predicator<T> mapper
) {
  final Subquery<T> subquery = cb.createQuery().subquery(clazz);
  final Root<T> root = subquery.from(clazz);
  final Predicate p = mapper.from(root);
  if (p != null) {
    subquery.where(p);
  }
  return subquery;
}

代码示例来源:origin: jamesagnew/hapi-fhir

Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
subQ.select(subQfrom.get("myResourceId").as(Long.class));
Subquery<Long> defJoin = subQ.subquery(Long.class);
Root<TagDefinition> defJoinFrom = defJoin.from(TagDefinition.class);
defJoin.select(defJoinFrom.get("myId").as(Long.class));
subQ.where(subQfrom.get("myTagId").as(Long.class).in(defJoin));
defJoin.where(toArray(orPredicates));

代码示例来源:origin: org.lorislab.armonitor/armonitor-ejb

Root<StoreSystem> project = sq.from(StoreSystem.class);
sq.select(project.join(StoreSystem_.roles).get(StoreRole_.guid)).where(cb.equal(project.get(StoreSystem_.guid), criteria.getSystem()));
sq.distinct(true);
predicates.add(cb.in(root.join(StoreUser_.roles).get(StoreRole_.guid)).value(sq));

代码示例来源:origin: JoleneOL/market-manage

static Expression<BigDecimal> currentGoodAdvancePaymentBalance(Expression<? extends Login> loginFrom
    , CriteriaBuilder cb, CriteriaQuery<?> cq) {
  Subquery<BigDecimal> add = cq.subquery(BigDecimal.class);
  Root<AgentGoodAdvancePayment> root = add.from(AgentGoodAdvancePayment.class);
  add = add
      .select(cb.sum(root.get(AgentGoodAdvancePayment_.amount)))
      .where(
          cb.equal(root.get(AgentGoodAdvancePayment_.login), loginFrom)
          , AgentGoodAdvancePayment.isSuccessPayment(root, cb)
      );
  Subquery<BigDecimal> ordered = cq.subquery(BigDecimal.class);
  // 减去非关闭的订单
  Root<AgentPrepaymentOrder> orderRoot = ordered.from(AgentPrepaymentOrder.class);
  ordered = ordered.select(cb.sum(orderRoot.get(AgentPrepaymentOrder_.goodTotalPriceAmountIndependent)))
      .where(cb.and(
          cb.equal(orderRoot.get(AgentPrepaymentOrder_.belongs), loginFrom)
          , cb.notEqual(orderRoot.get(AgentPrepaymentOrder_.orderStatus), OrderStatus.close)
      ));
  return cb.diff(cb.<Boolean, BigDecimal>selectCase(add.isNull())
          .when(true, BigDecimal.ZERO)
          .otherwise(add)
      , cb.<Boolean, BigDecimal>selectCase(ordered.isNull())
          .when(true, BigDecimal.ZERO)
          .otherwise(ordered));
}

代码示例来源:origin: org.kuali.rice/rice-krad-data

@Override
protected void addNotExistsSubquery(TranslationContext criteria, String subQueryType,
    org.kuali.rice.core.api.criteria.Predicate subQueryPredicate) {
  try {
    Class<?> subQueryBaseClass = Class.forName(subQueryType);
    Subquery<?> subquery = criteria.query.subquery(subQueryBaseClass);
    TranslationContext subQueryJpaPredicate = createCriteriaForSubQuery(subQueryBaseClass, criteria);
    // If a subQueryPredicate is passed, this is a Rice Predicate object and must be translated
    // into JPA - so we add it to the list this way.
    if (subQueryPredicate != null) {
      addPredicate(subQueryPredicate, subQueryJpaPredicate);
    }
    subquery.where(subQueryJpaPredicate.predicates.toArray(new Predicate[0]));
    criteria.addNotExistsSubquery(subquery);
  } catch (ClassNotFoundException e) {
      throw new IllegalArgumentException(subQueryType + " can not be resolved to a class for JPA");
  }
}

代码示例来源:origin: org.jboss.pressgang.ccms/pressgang-ccms-query

topicSubquery.select((Root<Topic>) getRootPath());
topicSubquery.where(topicSubqueryCondition);

代码示例来源:origin: SAP/olingo-jpa-processor-v4

@SuppressWarnings("unchecked")
protected <T> void createSelectClauseAggregation(final Subquery<T> subQuery, final From<?, ?> from,
  final List<JPAOnConditionItem> conditionItems) {
 Path<?> p = from;
 for (final JPAElement jpaPathElement : conditionItems.get(0).getLeftPath().getPath())
  p = p.get(jpaPathElement.getInternalName());
 subQuery.select((Expression<T>) p);
}

代码示例来源:origin: org.jboss.pressgang.ccms/pressgang-ccms-query

protected BaseTopicFilterQueryBuilder(final Class<T> clazz, final BaseFieldFilter fieldFilter, final EntityManager entityManager,
    final boolean useTopicSubquery) {
  super(clazz, fieldFilter, entityManager);
  this.useTopicSubquery = useTopicSubquery;
  if (useTopicSubquery) {
    topicQuery = super.getCriteriaQuery().subquery(Topic.class);
    from = topicQuery.from(Topic.class);
  } else {
    topicQuery = null;
    from = null;
  }
}

代码示例来源:origin: org.omnifaces/omnipersistence

private <T extends E> Map<String, Object> buildCountSubquery(PageBuilder<T> pageBuilder, CriteriaQuery<Long> countQuery, Root<E> countRoot, CriteriaBuilder criteriaBuilder) {
  Subquery<T> countSubquery = countQuery.subquery(pageBuilder.getResultType());
  Root<E> countSubqueryRoot = buildRoot(countSubquery);
  PathResolver subqueryPathResolver = buildSelection(pageBuilder, countSubquery, countSubqueryRoot, criteriaBuilder);
  Map<String, Object> parameters = buildRestrictions(pageBuilder, countSubquery, criteriaBuilder, subqueryPathResolver);
  if (provider == HIBERNATE) {
    // SELECT COUNT(e) FROM E e WHERE e IN (SELECT t FROM T t WHERE [restrictions])
    countQuery.where(criteriaBuilder.in(countRoot).value(countSubquery));
    // EclipseLink (tested 2.6.4) fails here with an incorrect selection in subquery: SQLException: Database "T1" not found; SQL statement: SELECT COUNT(t0.ID) FROM PERSON t0 WHERE t0.ID IN (SELECT DISTINCT t1.ID.t1.ID FROM PERSON t1 WHERE [...])
    // OpenJPA (tested 2.4.2) fails here as it doesn't interpret root as @Id: org.apache.openjpa.persistence.ArgumentException: Filter invalid. Cannot compare value of type optimusfaces.test.Person to value of type java.lang.Long.
  }
  else if (provider == OPENJPA) {
    // SELECT COUNT(e) FROM E e WHERE e.id IN (SELECT t.id FROM T t WHERE [restrictions])
    countQuery.where(criteriaBuilder.in(countRoot.get(ID)).value(countSubquery));
    // Hibernate (tested 5.0.10) fails here when DTO is used as it does not have a mapped ID.
    // EclipseLink (tested 2.6.4) fails here with an incorrect selection in subquery: SQLException: Database "T1" not found; SQL statement: SELECT COUNT(t0.ID) FROM PERSON t0 WHERE t0.ID IN (SELECT DISTINCT t1.ID.t1.ID FROM PERSON t1 WHERE [...])
  }
  else {
    // SELECT COUNT(e) FROM E e WHERE EXISTS (SELECT t.id FROM T t WHERE [restrictions] AND t.id = e.id)
    countQuery.where(criteriaBuilder.exists(countSubquery.where(conjunctRestrictionsIfNecessary(criteriaBuilder, countSubquery.getRestriction(), criteriaBuilder.equal(countSubqueryRoot.get(ID), countRoot.get(ID))))));
    // Hibernate (tested 5.0.10) and OpenJPA (tested 2.4.2) also support this but this is a tad less efficient than IN.
  }
  return parameters;
}

代码示例来源:origin: SAP/olingo-jpa-processor-v4

protected void handleAggregation(final Subquery<?> subQuery, final From<?, ?> subRoot,
  final List<JPAOnConditionItem> conditionItems) throws ODataApplicationException {
 final List<Expression<?>> groupByLIst = new ArrayList<>();
 if (filterComplier != null && this.aggregationType != null) {
  for (final JPAOnConditionItem onItem : conditionItems) {
   Path<?> subPath = subRoot;
   for (final JPAElement jpaPathElement : onItem.getRightPath().getPath())
    subPath = subPath.get(jpaPathElement.getInternalName());
   groupByLIst.add(subPath);
  }
  subQuery.groupBy(groupByLIst);
  try {
   subQuery.having(this.filterComplier.compile());
  } catch (ExpressionVisitException e) {
   throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
  }
 }
}

代码示例来源:origin: org.jboss.pressgang.ccms/pressgang-ccms-query

/**
 * Create a Subquery to get the latest revision for a translated topic and locale.
 *
 * @return A subquery that will return the maximum revision for a translated topic and locale.
 */
protected Subquery<Integer> getLatestRevisionSubquery() {
  final CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
  final Subquery<Integer> subQuery = getCriteriaQuery().subquery(Integer.class);
  final Root<TranslatedTopicData> root = subQuery.from(TranslatedTopicData.class);
  subQuery.select(criteriaBuilder.max(root.get("translatedTopic").get("topicRevision").as(Integer.class)));
  final Predicate topicIdMatch = criteriaBuilder.equal(root.get("translatedTopic").get("topicId"), translatedTopic.get("topicId"));
  final Predicate localeMatch = criteriaBuilder.equal(getOriginalRootPath().get("translationLocale"), root.get("translationLocale"));
  subQuery.where(criteriaBuilder.and(topicIdMatch, localeMatch));
  subQuery.groupBy(root.get("translatedTopic").get("topicId"));
  return subQuery;
}

代码示例来源:origin: Jasig/uPortal

@Override
  public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
    final CriteriaQuery<DateDimensionImpl> criteriaQuery =
        cb.createQuery(DateDimensionImpl.class);
    final Root<DateDimensionImpl> dimensionRoot =
        criteriaQuery.from(DateDimensionImpl.class);
    // Build subquery for max date
    final Subquery<LocalDate> maxDateSub =
        criteriaQuery.subquery(LocalDate.class);
    final Root<DateDimensionImpl> maxDateDimensionSub =
        maxDateSub.from(DateDimensionImpl.class);
    maxDateSub.select(
        cb.least(maxDateDimensionSub.get(DateDimensionImpl_.date)));
    // Get the date dimension
    criteriaQuery
        .select(dimensionRoot)
        .where(
            cb.equal(
                dimensionRoot.get(DateDimensionImpl_.date),
                maxDateSub));
    return criteriaQuery;
  }
});

代码示例来源:origin: org.jboss.pressgang.ccms/pressgang-ccms-query

@Override
public Predicate getMatchingLocaleString(final String locale) {
  final CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
  final Subquery<LanguageFile> subquery = getCriteriaQuery().subquery(LanguageFile.class);
  final Root<LanguageFile> from = subquery.from(LanguageFile.class);
  final Predicate languageFileEqual = criteriaBuilder.equal(getRootPath(), from.get("file"));
  final Predicate localeEqual = criteriaBuilder.equal(from.get("locale").get("value"), locale);
  subquery.where(criteriaBuilder.and(languageFileEqual, localeEqual));
  return criteriaBuilder.exists(subquery);
}

代码示例来源:origin: org.kuali.rice/rice-krad-data

/**
 * {@inheritDoc}
 */
@Override
protected void addExistsSubquery(TranslationContext criteria, String subQueryType,
    org.kuali.rice.core.api.criteria.Predicate subQueryPredicate) {
  try {
    Class<?> subQueryBaseClass = Class.forName(subQueryType);
    Subquery<?> subquery = criteria.query.subquery(subQueryBaseClass);
    TranslationContext subQueryJpaPredicate = createCriteriaForSubQuery(subQueryBaseClass, criteria);
    // If a subQueryPredicate is passed, this is a Rice Predicate object and must be translated
    // into JPA - so we add it to the list this way.
    if (subQueryPredicate != null) {
      addPredicate(subQueryPredicate, subQueryJpaPredicate);
    }
    subquery.where(subQueryJpaPredicate.predicates.toArray(new Predicate[0]));
    criteria.addExistsSubquery(subquery);
  } catch (ClassNotFoundException e) {
    throw new IllegalArgumentException(subQueryType + " can not be resolved to a class for JPA");
  }
}

代码示例来源:origin: SAP/olingo-jpa-processor-v4

@SuppressWarnings("unchecked")
protected <T> void createSelectClause(final Subquery<T> subQuery, final From<?, ?> from,
  final List<JPAOnConditionItem> conditionItems) {
 Path<?> p = from;
 for (final JPAElement jpaPathElement : conditionItems.get(0).getRightPath().getPath())
  p = p.get(jpaPathElement.getInternalName());
 subQuery.select((Expression<T>) p);
}

相关文章