How do I write a MAX query with a where clause in JPA 2.0?

前端 未结 2 1047
心在旅途
心在旅途 2020-12-15 19:48

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         


        
相关标签:
2条回答
  • 2020-12-15 19:52

    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")));
    
    0 讨论(0)
  • 2020-12-15 20:12

    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();
    
    0 讨论(0)
提交回复
热议问题