![](/img/trans.png)
[英]JPA + Hibernate - How to get FK of child entity without fetching that entity?
[英]How do I get the foreign key column value of a dependent Hibernate Entity without fetching the full entity?
我正在努力解決一個似乎太容易的問題:
安裝程序是兩個在Hibernate 3中具有多對一關系的實體:
@Entity
class M {
private N n;
@ManyToOne(fetch = FetchType.LAZY)
public N getN() { return n; }
public void setN(N n) { this.n = n; }
}
@Entity
class N {
private List<M> ms = new ArrayList<M>();
@OneToMany(mappedBy="n")
public List<M> getMs() { return ms; }
public void setMs(List<M> ms) { this.ms = ms; }
}
很容易。 在我的應用程序中,我有一個M
的列表,要么有N
,要么沒有。 此列表是h:dataTable
的輸入,它根據FK是否為空顯示不同的列內容。 但是當我測試m.getN() != null
這會導致hibernate加載N
我怎么能避免這個?
編輯 :這實際上是我的錯誤,正如JBNizet在評論中指出的那樣。 為了至少使這對某人有用並與上面的布局保持一致,我將問題改為“如何在不獲取完整實體的情況下獲取依賴Hibernate實體的外鍵列值?” 正如Aaron Digulla所說。
編輯2 :結果新問題是這個問題的重復: 當我只訪問外鍵id時,如何防止Hibernate獲取連接的實體? - 所以,投票結束?
創建一個投影映射,其中包含M或M的幾個字段,例如N的id
您的查詢可能會像liook那樣
select new com.my.ProjectionObject(m, mnid) from M m where ...
您如何期待Hibernate告訴您它不知道的事情? 在不加載實體的情況下,Hibernate無法知道它是否仍然存在。
如果您走出Hibernate“實體映射器”框,您可以直接查詢數據庫,例如,計算M
的N
s數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.