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, , java 6. how write jpa query following psuedo-sql?
select max(e.dateprocessed) event e e.org = myorg
and domain object looks 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 criteriabuilder.greatest involved, can't figure out how write query. return event objects match organization, that's far 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());
there 2 ways, 1 using jpql, other using criteria queries.
jpql simply:
em.createquery("select max(e.dateprocessed) event e e.org = :myorg") .setparameter("myorg", myorg) .getsingleresult();
while using criteria 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();
Comments
Post a Comment