如何在JPA 2.0中使用where子句编写MAX查询?

编程入门 行业动态 更新时间:2024-10-27 20:38:31
本文介绍了如何在JPA 2.0中使用where子句编写MAX查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

我知道CriteriaBuilder.greatest是参与的,但我无法弄清楚如何编写查询。这将返回与组织相匹配的所有事件对象,但这是我已经得到的。

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

推荐答案

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

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

更多推荐

如何在JPA 2.0中使用where子句编写MAX查询?

本文发布于:2023-10-21 17:05:49,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   如何在   JPA   MAX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!