示例#1
1
 @Test
 public void max() {
   EntityManager entityManager = factory.createEntityManager();
   CriteriaBuilder builder = entityManager.getCriteriaBuilder();
   CriteriaQuery<Integer> query = builder.createQuery(Integer.class);
   Root<Employee> root = query.from(Employee.class);
   query.select(builder.max(root.get(Employee_.age)));
   int min = entityManager.createQuery(query).getSingleResult();
   assertEquals(70, min);
 }
  @Override
  protected T beforeInsert(T entity) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
    Root<? extends ChaveValor> productRoot = criteria.from(entity.getClass());
    criteria.select(builder.max(productRoot.get("codigo")));
    Long codigo = getEntityManager().createQuery(criteria).getSingleResult();

    if (codigo == null) {
      codigo = 1L;
    } else {
      codigo++;
    }
    entity.setCodigo(codigo);

    return super.beforeInsert(entity);
  }
示例#3
0
  /** This test provides a demonstration of the MIN and MAX aggregate functions */
  @Test
  public void testMaxMin() {
    log.info("*** testMaxMin() ***");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Number> qdef = cb.createQuery(Number.class);
    Root<Sale> s = qdef.from(Sale.class);

    // select max(s.amount) from Sale s
    qdef.select(cb.max(s.<BigDecimal>get("amount")));
    List<Number> results = executeQuery(qdef);
    assertEquals("unexpected number of rows", 1, results.size());
    assertEquals("unexpected result", 150, results.get(0).intValue());

    // select min(s.amount) from Sale s
    qdef.select(cb.min(s.<BigDecimal>get("amount")));
    results = executeQuery(qdef);
    assertEquals("unexpected number of rows", 1, results.size());
    assertEquals("unexpected result", 100, results.get(0).intValue());
  }
  /**
   * get the last updated timestamp in {@link StopEntity}
   *
   * @return timeStamp
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public Date lastUpdate() {

    try {
      // selectin the table for the required records
      CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
      CriteriaQuery<Date> maxQuery = criteriaBuilder.createQuery(Date.class);
      Root stopEntityRoot = maxQuery.from(StopEntity.class);

      // selecting the records the providing the criteria record with the max timeStamp value
      // it should not return multiple records
      maxQuery.select(criteriaBuilder.max(stopEntityRoot.<Date>get("timeStamp")));

      // to avoid problems only one record is returning here
      return getEntityManager().createQuery(maxQuery).getSingleResult();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }