對不起,這個相當基本的問題,但我必須得到某種原型的工作很快,這是我第一次進入JPA。JPA 2.0 CriteriaBuilder幫助 - 如何選擇匹配特定位置查詢的最大(最大)值?
我有一個類,系統有一個快照項目列表,每個都有一個數字ID和一個SystemID。
如何查詢快照這樣說:
select top 1 ID from Snapshots
where Snapshots.SystemID = X
order by Snapshots.ID desc;
我知道如何把那裏查詢中,不知道從哪裏把我的「最偉大」的位。
謝謝!
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,VS使用系統對象,找到特定系統的快照?
對不起,如果這是令人困惑!
我確實也有一對多的映射,I:
或者,如果你有系統的實體,您可以直接比較的對象:
使用CriteriaBuilder(和元模型)不知道如何指定該列,如上面 – Yablargo
所示,在這種情況下,您的Snapshot實體應與System(mappedBy)具有反向關係,從而使systemID屬性變爲冗餘;無論如何,請僅僅忽略那條評論 –
是的,我應該包括那個。我有一個Snapshot類,它具有映射回來的System屬性。但是說我有一個對應於系統ID的id(5) - 我想直接查詢,我可以這樣做嗎?我知道底層字段是systemID,並在快照類 – Yablargo