I\'m using JPA 2.0. Hibernate 4.1.0.Final, and Java 6. How do I write a JPA query from the following psuedo-SQL?
select max(e.dateProcessed) from Event e wh
With JPQL and CriteriaBuilder
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery cq= getEntityManager().getCriteriaBuilder().createQuery();
Root<T> c = cq.from(getEntityClass());
cq.select(cb.max(c.get("id")));
There are two ways, one using JPQL, the other using criteria queries.
JPQL is simply:
em.createQuery("select max(e.dateProcessed) from Event e where e.org = :myOrg")
.setParameter("myOrg", myOrg)
.getSingleResult();
while using criteria you might have:
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Number> cq = qb.createQuery(Number.class);
Root<Event> root = cq.from(Event.class);
cq.select(qb.max(root.get("dateProcessed")));
cq.where(qb.equal(Event.get("org"), qb.parameter(MyOrgType.class, "myOrg")));
em.createQuery(cq).setParameter("myOrg", myOrg).getSingleResult();