很抱歉这个相当基本的问题,但我必须让某种原型(prototype)快速工作,这是我第一次涉足 JPA。
我有一个类 System,它有一个快照项目列表,每个项目都有一个数字 ID 和一个 SystemID。
如何查询快照以说出类似以下内容:
select top 1 ID from Snapshots
where Snapshots.SystemID = X
order by Snapshots.ID desc;
我知道如何将 where 查询放入其中,但不确定将我的“最伟大”部分放在哪里。
谢谢!!
public Snapshot GetMostRecentSnapshotByID(int systemID) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<mynamespace.Snapshot> criteria =
cb.createQuery(mynamespace.Snapshot.class);
Root<mynamespace> snapshot = criteria.from(mynamespace.Snapshot.class);
criteria.where(cb.equal(snapshot.get(Snapshot_.systemID), systemID));
//OK -- where does this guy go?
cb.greatest(snapshot.get(Snapshot_.id));
return JPAResultHelper.getSingleResultOrNull(em.createQuery(criteria));
}
澄清:我的快照类有以下(片段) @
Entity
public class Snapshot implements Serializable {
@Id
@GeneratedValue
private int id;
@ManyToOne
@JoinColumn(name = "systemID", nullable = false)
private System system;
与使用系统对象相比,我可以查询数字 ID 来查找特定系统的快照吗?
抱歉,如果这让您感到困惑!
最佳答案
您对 jpa 使用实体和属性而不是表和列有点困惑;如果您正在学习,我建议您首先尝试使用 jpql 实现查询,例如:
String q = "from Snapshot s where s.systemID = :systemID order by s.id desc";
TypedQuery<Snapshot> query = em.createTypedQuery(q, Snapshot.class);
query.setParameter("systemID", systemID);
return query.getFirstResult();
// return a Snapshot object, get the id with the getter
(将 (@OneToMany) 快照映射到系统实体而不是使用原始 ID 会更好)
那么你可以尝试使用 CriteriaBuilder(这里不使用元模型):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Object> cq = cb.createQuery();
Root<Snapshot> r = cq.from(Snapshot.class);
cq.where(cb.equal(r.get("systemID"), systemID));
cd.orderBy(cb.desc(r.get("id")));
em.createQuery(cq).geFirsttResult();
如果你想创建一个where...and...
(但这不是你在这个问题中的情况),它会是:
[...]
Predicate p1 = cb.equal(r.get("systemID"), systemID));
Predicate p2 = cb. /* other predicate */
cb.and(p1,p2);
[...]
编辑:
Can I query against a numerical id, vs using a System object, to find a particular System's snapshots?
当然,你可以这样做(假设系统有一个名为 id 的 @Id 属性):
String q = "from Snapshot s where s.system.id = :systemID order by s.id desc";
[...]
其中 s.system.id 表示:s(快照)的属性系统(类 System)的属性 id(整数)。
或者,如果您有系统实体,您可以直接比较对象:
String q = "from Snapshot s where s.system = :system order by s.id desc";
query.setParameter("system", system);
[...]
使用 CriteriaBuilder(和元模型):
Metamodel m = em.getMetamodel();
Root<Snapshot> snapshot = cq.from(Snapshot.class);
Join<Snapshot, System> system = snapshot.join(Snapshot_.system);
cq.where(cb.equal(System_.id, systemID));
[...]
关于java - JPA 2.0 CriteriaBuilder 帮助 - 如何选择与特定 where 查询匹配的最大(最大值)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12568296/