javax.persistence.criteria.CriteriaQuery.multiselect()方法的使用及代码示例

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

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

CriteriaQuery.multiselect介绍

[英]Specify the selection items that are to be returned in the query result. Replaces the previously specified selection(s), if any.

The type of the result of the query execution depends on the specification of the type of the criteria query object created as well as the argument to the multiselect method. An element of the list passed to the multiselect method must not be a tuple- or array-valued compound selection item.

The semantics of this method are as follows:

  • If the type of the criteria query is CriteriaQuery<Tuple> (i.e., a criteria query object created by either the createTupleQuery method or by passing a Tuple class argument to the createQuery method), a Tuple object corresponding to the elements of the list passed to the multiselect method, in the specified order, will be instantiated and returned for each row that results from the query execution.
  • If the type of the criteria query is CriteriaQuery<X> for some user-defined class X (i.e., a criteria query object created by passing a X class argument to the createQuery method), the elements of the list passed to the multiselect method will be passed to the X constructor and an instance of type X will be returned for each row.
  • If the type of the criteria query is CriteriaQuery<X[]> for some class X, an instance of type X[] will be returned for each row. The elements of the array will correspond to the elements of the list passed to the multiselect method, in the specified order.
  • If the type of the criteria query is CriteriaQuery<Object> or if the criteria query was created without specifying a type, and the list passed to the multiselect method contains only a single element, an instance of type Object will be returned for each row.
  • If the type of the criteria query is CriteriaQuery<Object> or if the criteria query was created without specifying a type, and the list passed to the multiselect method contains more than one element, an instance of type Object[] will be instantiated and returned for each row. The elements of the array will correspond to the elements of the list passed to the multiselect method, in the specified order.
    [中]指定要在查询结果中返回的选择项。替换以前指定的选择(如果有)。
    查询执行结果的类型取决于创建的条件查询对象类型的规范以及multiselect方法的参数。传递给multiselect方法的列表元素不能是元组值或数组值的复合选择项。
    此方法的语义如下所示:
    *如果条件查询的类型为CriteriaQuery<Tuple>(即,通过createTupleQuery方法或通过将Tuple类参数传递给createQuery方法创建的条件查询对象),则按照指定顺序传递给multiselect方法的列表元素对应的Tuple对象,将为查询执行产生的每一行实例化并返回。
    *如果某个用户定义类X的条件查询类型为CriteriaQuery<X>(即,通过将X类参数传递给createQuery方法创建的条件查询对象),则传递给multiselect方法的列表元素将传递给X构造函数,并为每一行返回类型为X的实例。
    *如果某个类X的条件查询类型为CriteriaQuery<X[]>,则将为每一行返回类型为X[]的实例。数组的元素将按照指定的顺序与传递给multiselect方法的列表元素相对应。
    *如果条件查询的类型为CriteriaQuery<Object>,或者如果创建条件查询时未指定类型,并且传递给multiselect方法的列表仅包含单个元素,则将为每行返回Object类型的实例。
    *如果条件查询的类型为CriteriaQuery<Object>,或者如果创建条件查询时未指定类型,并且传递给multiselect方法的列表包含多个元素,则将实例化Object[]类型的实例,并为每行返回该实例。数组的元素将按照指定的顺序与传递给multiselect方法的列表元素相对应。

代码示例

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

@Test
public void test_criteria_typedquery_multiselect_implicit_array_example() {
  doInJPA( this::entityManagerFactory, entityManager -> {
    //tag::criteria-typedquery-multiselect-array-implicit-example[]
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteria = builder.createQuery( Object[].class );
    Root<Person> root = criteria.from( Person.class );
    Path<Long> idPath = root.get( Person_.id );
    Path<String> nickNamePath = root.get( Person_.nickName);
    criteria.multiselect( idPath, nickNamePath );
    criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) );
    List<Object[]> idAndNickNames = entityManager.createQuery( criteria ).getResultList();
    //end::criteria-typedquery-multiselect-array-implicit-example[]
    assertEquals(1, idAndNickNames.size());
  });
}

代码示例来源:origin: spring-projects/spring-data-jpa

query = query.multiselect(selections);
  query = query.multiselect(root.get((SingularAttribute) id).alias(id.getName()));
  query = query.multiselect(root.getModel().getIdClassAttributes().stream()//
      .map(it -> (Selection<?>) root.get((SingularAttribute) it).alias(it.getName()))
      .collect(Collectors.toList()));

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

@Test
public void test_criteria_from_multiple_root_example() {
  doInJPA( this::entityManagerFactory, entityManager -> {
    String address = "Earth";
    String prefix = "J%";
    //tag::criteria-from-multiple-root-example[]
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createQuery( Tuple.class );
    Root<Person> personRoot = criteria.from( Person.class );
    Root<Partner> partnerRoot = criteria.from( Partner.class );
    criteria.multiselect( personRoot, partnerRoot );
    Predicate personRestriction = builder.and(
      builder.equal( personRoot.get( Person_.address ), address ),
      builder.isNotEmpty( personRoot.get( Person_.phones ) )
    );
    Predicate partnerRestriction = builder.and(
      builder.like( partnerRoot.get( Partner_.name ), prefix ),
      builder.equal( partnerRoot.get( Partner_.version ), 0 )
    );
    criteria.where( builder.and( personRestriction, partnerRestriction ) );
    List<Tuple> tuples = entityManager.createQuery( criteria ).getResultList();
    //end::criteria-from-multiple-root-example[]
    assertEquals(2, tuples.size());
  });
}

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

@Test
public void test_criteria_group_by_example() {
  doInJPA( this::entityManagerFactory, entityManager -> {
    //tag::criteria-group-by-example[]
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createQuery( Tuple.class );
    Root<Person> root = criteria.from( Person.class );
    criteria.groupBy(root.get("address"));
    criteria.multiselect(root.get("address"), builder.count(root));
    List<Tuple> tuples = entityManager.createQuery( criteria ).getResultList();
    for ( Tuple tuple : tuples ) {
      String name = (String) tuple.get( 0 );
      Long count = (Long) tuple.get( 1 );
    }
    //end::criteria-group-by-example[]
    assertEquals(2, tuples.size());
  });
}

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

@Test
public void test_criteria_tuple_example() {
  doInJPA( this::entityManagerFactory, entityManager -> {
    //tag::criteria-tuple-example[]
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createQuery( Tuple.class );
    Root<Person> root = criteria.from( Person.class );
    Path<Long> idPath = root.get( Person_.id );
    Path<String> nickNamePath = root.get( Person_.nickName);
    criteria.multiselect( idPath, nickNamePath );
    criteria.where( builder.equal( root.get( Person_.name ), "John Doe" ) );
    List<Tuple> tuples = entityManager.createQuery( criteria ).getResultList();
    for ( Tuple tuple : tuples ) {
      Long id = tuple.get( idPath );
      String nickName = tuple.get( nickNamePath );
    }
    //or using indices
    for ( Tuple tuple : tuples ) {
      Long id = (Long) tuple.get( 0 );
      String nickName = (String) tuple.get( 1 );
    }
    //end::criteria-tuple-example[]
    assertEquals(1, tuples.size());
  });
}

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

criteriaQuery = criteriaQuery.multiselect(

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

@Test
@TestForIssue(jiraKey = "HHH-11743")
public void testTupleStream() {
  doInHibernate( this::sessionFactory, session -> {
    MyEntity entity = new MyEntity();
    entity.id = 2;
    entity.name = "an entity";
    session.persist( entity );
  } );
  //test tuple stream using criteria
  doInHibernate( this::sessionFactory, session -> {
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = cb.createTupleQuery();
    Root<MyEntity> me = criteria.from( MyEntity.class );
    criteria.multiselect( me.get( "id" ), me.get( "name" ) );
    Stream<Tuple> data = session.createQuery( criteria ).stream();
    data.forEach( tuple -> assertTyping( Tuple.class, tuple ) );
  } );
  //test tuple stream using JPQL
  doInHibernate( this::sessionFactory, session -> {
    Stream<Tuple> data = session.createQuery( "SELECT me.id, me.name FROM MyEntity me", Tuple.class ).stream();
    data.forEach( tuple -> assertTyping( Tuple.class, tuple ) );
  } );
}

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

private void findMatchingTagIds(String theResourceName, IIdType theResourceId, Set<Long> tagIds, Class<? extends BaseTag> entityClass) {
  {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = builder.createTupleQuery();
    Root<? extends BaseTag> from = cq.from(entityClass);
    cq.multiselect(from.get("myTagId").as(Long.class)).distinct(true);
    if (theResourceName != null) {
      Predicate typePredicate = builder.equal(from.get("myResourceType"), theResourceName);
      if (theResourceId != null) {
        cq.where(typePredicate, builder.equal(from.get("myResourceId"), myIdHelperService.translateForcedIdToPid(theResourceName, theResourceId.getIdPart())));
      } else {
        cq.where(typePredicate);
      }
    }
    TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
    for (Tuple next : query.getResultList()) {
      tagIds.add(next.get(0, Long.class));
    }
  }
}

代码示例来源:origin: zstackio/zstack

private void done() {
  if (_selects.size() == 0) {
    _query = _builder.createQuery(_entityClass);
  } else if (_selects.size() == 1) {
    Class<?> selectType = _selects.get(0)._javaType;
    _query = _builder.createQuery(selectType);
  } else {
    _query = _builder.createTupleQuery(); 
  }
  
  _root = _query.from(_entityClass);
  
  if (_selects.size() == 0) {
  } else if (_selects.size() == 1) {
    Path p = _root.get(_selects.get(0)._attr);
    _query.select(p);
  } else {
    for (AttrInfo info : _selects) {
      _paths.add(_root.get(info._attr)); 
    }
    _query.multiselect(_paths);
  }
  _query.where(whereClause());
  _query.orderBy(orderClause());
  groupByClause(_query);
}

代码示例来源:origin: Impetus/Kundera

@Test
public void testMultiSelectedClause()
{
  String expected = "Select p.personName,p.age from Person p";
  CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
  // Check for multi column select
  CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);
  Root<Person> from = personQuery.from(Person.class);
  personQuery.multiselect((Selection) from.get("personName").alias("p"), (Selection) from.get("age").alias("p"));
  String actual = CriteriaQueryTranslator.translate(personQuery);
  Assert.assertEquals(expected.trim(), actual.trim());
}

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

myResourceTableRoot = myResourceTableQuery.from(ResourceTable.class);
if (theCount) {
  outerQuery.multiselect(myBuilder.countDistinct(myResourceTableRoot));
} else {
  outerQuery.multiselect(myResourceTableRoot.get("myId").as(Long.class));
myResourceTableRoot = myResourceTableQuery.from(ResourceTable.class);
if (theCount) {
  outerQuery.multiselect(myBuilder.countDistinct(myResourceTableRoot));
} else {
  outerQuery.multiselect(myResourceTableRoot.get("myId").as(Long.class));

代码示例来源:origin: stackoverflow.com

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Friend> c = query.from(Friend.class);
query.multiselect(c.get(Friend_.firstName),c.get(Friend_.lastName)).distinct(true);

代码示例来源:origin: uaihebert/uaicriteria

private void addMultiSelectMultiSelectValues() {
  if (multiselectSelectList.isEmpty()) {
    throw new IllegalStateException("You want to extract a multiselect query, but you have not added any attribute or method to the query");
  }
  final Selection[] multiselectSelectArray = new Selection[multiselectSelectList.size()];
  multiselectSelectList.toArray(multiselectSelectArray);
  getConvertedCriteriaQuery().multiselect(multiselectSelectArray);
}

代码示例来源:origin: onsoul/HA-DB

private <S> S aggregate(CriteriaBuilder builder, CriteriaQuery<S> query, Root<E> root, Specification<E> spec, List<Selection<?>> selectionList, LockModeType lockMode) {
  if (selectionList != null) {
    Predicate predicate = spec.toPredicate(root, query, builder);
    if (predicate != null) {
      query.where(predicate);
    }
    query.multiselect(selectionList);
    return (S) em.createQuery(query).setLockMode(lockMode).getSingleResult();
  }
  return null;
}

代码示例来源:origin: katharsis-project/katharsis-framework

@Override
public void addSelection(Expression<?> expression, String name) {
  Selection<?> selection = criteriaQuery.getSelection();
  List<Selection<?>> newSelection = new ArrayList<>();
  if (selection != null) {
    if (selection.isCompoundSelection()) {
      newSelection.addAll(selection.getCompoundSelectionItems());
    }
    else {
      newSelection.add(selection);
    }
  }
  newSelection.add(expression);
  criteriaQuery.multiselect(newSelection);
}

代码示例来源:origin: org.fornax.cartridges/fornax-cartridges-sculptor-framework

@SuppressWarnings("unchecked")
protected void prepareSelect(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
  if (expressions.hasSelections()) {
    List<Selection<?>> selections = mapSelections(getCriteriaBuilder(), root, expressions.getSelections());
    if (selections.size() == 1) {
      criteriaQuery.select((Selection<? extends R>) selections.get(0));
    } else {
      criteriaQuery.multiselect(selections);
    }
  }
}

代码示例来源:origin: pl.edu.icm.cocos/cocos-services

@Override
  public List<Tuple> group(GroupingSpecification<T> specification) {
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<Tuple> query = cb.createTupleQuery();

    final Root<T> root = query.from(getDomainClass());
    root.alias(SELECTION_OUTPUT);
    final Map<Expression<?>, String> paths = specification.buildPaths(root, cb);

    query.multiselect(specification.toSelect(paths, root, cb));
    query.where(specification.toPredicate(root, query, cb));
    query.groupBy(new ArrayList<>(paths.keySet()));
    

    return em.createQuery(query).getResultList();
  }
}

代码示例来源:origin: net.e6tech/elements-persist

public <R> R getSingleResult() {
  where.onQuery();
  if (selections.size() == 1) {
    getQuery().select((Selection<? extends T>) selections.get(0));
  } else if (!selections.isEmpty()) {
    getQuery().multiselect(selections);
  } else {
    getQuery().select(getFrom());
  }
  Query query = where.getEntityManager().createQuery(getQuery());
  if (maxResults >= 0)
    query.setMaxResults(maxResults);
  if (firstResult >= 0)
    query.setFirstResult(firstResult);
  return (R) query.getSingleResult();
}

代码示例来源:origin: vladmihalcea/high-performance-java-persistence

@Test
public void testFetchObjectArray() {
  doInJPA(entityManager -> {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteria = builder.createQuery(Object[].class);
    Root<PostComment> root = criteria.from(PostComment.class);
    criteria.multiselect(root.get(PostComment_.id), root.get(PostComment_.review));
    Join<PostComment, Post> postJoin = root.join("post");
    criteria.where(builder.like(postJoin.get(Post_.title), "high-performance%"));
    List<Object[]> comments = entityManager.createQuery(criteria).getResultList();
    assertEquals(5, comments.size());
  });
}

代码示例来源:origin: vladmihalcea/high-performance-java-persistence

@Test
  public void testTuple() {
    doInJPA(entityManager -> {
      CriteriaBuilder cb = entityManager.getCriteriaBuilder();
      CriteriaQuery<Tuple> cq = cb.createTupleQuery();

      Root<BlogEntityProvider.Post> postRoot = cq.from(BlogEntityProvider.Post.class);
      Path<Long> idPath = postRoot.get("id");
      Path<String> titlePath = postRoot.get("title");
      cq.multiselect(idPath, titlePath);

      List<Tuple> resultList = entityManager.createQuery(cq).getResultList();

      for (Tuple tuple : resultList) {
        Long id = tuple.get(idPath);
        String title = tuple.get(titlePath);
      }
    });
  }
}

相关文章