Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

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

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 where e.org = myOrg

And my domain object looks like the following:

@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;

I know that CriteriaBuilder.greatest is involved, but I just can't figure out how to write the query. This will return all the event objects that match the organization, but that's as far as I've gotten.

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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...