Exemplo n.º 1
0
  /**
   * This test provides another demonstration of selecting multiple properties -- with this example
   * using a constructor expression to return a typed object for each result in the query.
   */
  @Test
  public void testMultiSelectConstructor() {
    log.info("*** testMultiSelectConstructor() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Receipt> qdef = cb.createQuery(Receipt.class);

    // select new ejava.jpa.examples.query.Receipt(s.id,s.buyerId,s.date, s.amount)
    // from Sale s
    Root<Sale> s = qdef.from(Sale.class);
    qdef.select(
        cb.construct(Receipt.class, s.get("id"), s.get("buyerId"), s.get("date"), s.get("amount")));

    TypedQuery<Receipt> query = em.createQuery(qdef);
    List<Receipt> results = query.getResultList();
    assertTrue("no results", results.size() > 0);
    for (Receipt receipt : results) {
      assertNotNull("no receipt", receipt);
      log.info("receipt=" + receipt);
    }
  }
  @Override
  public <C, X> Page<C> findAll(
      Specification<T> spec, Class<C> clazz, Selections<T, C, X> selection, Pageable pageable) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<C> query = builder.createQuery(clazz);
    Root<T> root = query.from(getDomainClass());
    Predicate predicate = spec.toPredicate(root, query, builder);

    if (predicate != null) {
      query.where(predicate);
    }
    query.select(builder.construct(clazz, selection.select(root, query, builder)));
    List<Expression<?>> groupBy = query.getGroupList();
    Predicate having = query.getGroupRestriction();
    if (pageable.getSort() != null) {
      query.orderBy(toOrders(pageable.getSort(), root, builder));
    }
    TypedQuery<C> typeQuery = em.createQuery(query);
    return pageable == null
        ? new PageImpl<>(typeQuery.getResultList())
        : readPage(typeQuery, pageable, spec, selection, groupBy, having);
  }