@Test
  public void testQuotientAndMultiply() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    CriteriaQuery<Number> criteria = builder.createQuery(Number.class);
    criteria.from(Product.class);
    criteria.select(
        builder.quot(
            builder.prod(
                builder.literal(BigDecimal.valueOf(10.0)),
                builder.literal(BigDecimal.valueOf(5.0))),
            BigDecimal.valueOf(2.0)));
    Number result = em.createQuery(criteria).getSingleResult();
    assertEquals(25.0d, result.doubleValue(), 0.1d);

    criteria.select(
        builder.prod(
            builder.quot(
                builder.literal(BigDecimal.valueOf(10.0)),
                builder.literal(BigDecimal.valueOf(5.0))),
            BigDecimal.valueOf(2.0)));
    result = em.createQuery(criteria).getSingleResult();
    assertEquals(4.0d, result.doubleValue(), 0.1d);

    em.getTransaction().commit();
    em.close();
  }
Esempio n. 2
0
  /** This test provides a demonstration of using a math formual within the where clause. */
  @Test
  public void testFormulas() {
    log.info("*** testFormulas() ***");

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

    // select count(s) from Sale s
    // where (s.amount * :tax) > :amount"
    Root<Sale> s = qdef.from(Sale.class);
    qdef.select(cb.count(s))
        .where(
            cb.greaterThan(
                cb.prod(s.<BigDecimal>get("amount"), cb.parameter(BigDecimal.class, "tax")),
                new BigDecimal(10.0)));
    TypedQuery<Number> query = em.createQuery(qdef);

    // keep raising taxes until somebody pays $10.00 in tax
    double tax = 0.05;
    for (;
        query.setParameter("tax", new BigDecimal(tax)).getSingleResult().intValue() == 0;
        tax += 0.01) {
      log.debug("tax=" + NumberFormat.getPercentInstance().format(tax));
    }
    log.info("raise taxes to: " + NumberFormat.getPercentInstance().format(tax));

    assertEquals("unexpected level for tax:" + tax, 0.07, tax, .01);
  }