![](/img/trans.png)
[英]Hibernate JPA Entity how to save @Entity which have @OnetoMany @Entity inside that @Entity another @OnetoMany
[英]How to retrieve an entity which is an attribute for another entity with the less overhead possible?
我有以下實體:
@Entity
public class A{
...
@ManyToOne( optional=false, fetch=FetchType.LAZY )
@NotFound( action=NotFoundAction.EXCEPTION )
@JoinColumn( name="ID_CLASSB", nullable=false, insertable=true, updatable=true )
private B b;
...
private String anIdentifier;
...
@OneToMany(fetch=FetchType.LAZY)...
private List<C> manyObjects;
...
@OneToMany(fetch=FetchType.LAZY)...
private List<D> soMany;
}
如您所見,實體B是實體A中的一個屬性。
B實體沒有對A實體的引用,並且由簡單的屬性制成:
@Entity
public class B{
@Column(...)
private String field1;
@Column(...)
private int field2;
...
}
現在,我想從“ anIdentifier”屬性與特定值匹配的A實體中檢索所有B實體。 目前,我的查詢是:
"select a.b from A a where a.anIdentifier='identifier'"
問題是第二個查詢特別慢...而且我想這是因為休眠狀態在提取實體B之前仍會創建整個實體A(並因此創建其所有屬性)。
那么,還有另一種最有效的方式來實現我的目標嗎?
這是一個簡單的查詢,它應該可以快速運行。 是否獲取A的事實不會影響它,因為關系將被延遲加載(盡管可能未獲取A)
它變慢的典型原因是:-A到B關系的外鍵上沒有索引(表A的ID_CLASSB),-DB中有很多As,而anIdentifier上沒有索引
因此,請首先檢查它們在數據庫中的存在。
通常,您需要能夠查看生成的sql,以便能夠推理(和測試)性能。 您可以檢查此答案的完成情況休眠狀態使用休眠狀態時如何打印帶有參數值的查詢字符串
有了真正的查詢后,就可以在數據庫中進行測試,例如在MySQL中進行測試,這就是explain命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.