19

我正在使用 JPA 2.0。Hibernate 4.1.0.Final 和 Java 6。如何从以下伪 SQL 编写 JPA 查询?

select max(e.dateProcessed) from Event e where e.org = myOrg

我的域对象如下所示:

@GenericGenerator(name = "uuid-strategy", strategy = "org.mainco.subco.core.util.subcoUUIDGenerator")
@Entity
@Table(name = "sb__event",
    uniqueConstraints = { @UniqueConstraint(columnNames={"EVENT_ID"}) }
)
public class Event
{

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "uuid-strategy")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.REMOVE})
    @JoinColumn(name = "ORGANIZATION_ID", nullable = false, updatable = true)
    private Organization org;

    @Column(name = "DATE_PROCESSED")
    @NotNull
    private java.util.Date dateProcessed;

我知道涉及到 CriteriaBuilder.greatest,但我就是不知道如何编写查询。这将返回与组织匹配的所有事件对象,但这是我所得到的。

final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery<Event> criteria = builder.createQuery(Event.class);
final Root<Event> event = criteria.from(Event.class);
criteria.select(event);
criteria.where(builder.equal(Event.get("org"), org));
results.addAll(m_entityManager.createQuery(criteria).getResultList());
4

2 回答 2

35

有两种方法,一种使用 JPQL,另一种使用条件查询。
JPQL 很简单:

em.createQuery("select max(e.dateProcessed) from Event e where e.org = :myOrg")
  .setParameter("myOrg", myOrg)
  .getSingleResult();

在使用标准时,您可能有:

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();
于 2013-05-08T13:23:48.393 回答
0

使用 JPQL 和 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")));
于 2017-07-18T19:53:39.490 回答