2012-09-07 116 views
3

我有這樣的結構:休眠:更新子對象

// all objects have valid mapping to database 
public class Child { 
    private int id; 
    private String name; 
} 
public class Parent { 
    private int id; 
    private String name; 
    private List<Child> chidlren; 
} 

,我必須更新父A.內部具體小孩B

有兩種方式:

  1. 更新孩子的收集並更新整個對象內的字段:
    Parent temp = dao.getParent(id);
    temp.getChildren.get(0).setName('test');
    dao.updateParent(temp);

  2. 更新獨生子女對象:
    Child temp = dao.getChild(id);
    temp.setName('test');
    dao.updateChild(temp);

哪一個是,如果我想獲得更多的性能比較好?

謝謝

+0

你試過分析嗎?我認爲他們幾乎是一樣的,因爲如果優化,hibernate會做很多工作 – RNJ

+0

我的觀點是即使使用hibernate優化,第二種解決方案也會更快。如果你沒有任何額外的查詢,當然。我只是想聽到另一種想法 – nKognito

回答

1

從表面上看,我會猜測,第二個解決方案

只有2.更新子對象

會更好的性能。

但是,您定量確定此問題的唯一方法是打開Hibernate的show_sql,捕獲解決方案1和解決方案2的SQL,爲您的每個解決方案運行解釋計劃,並比較解釋計劃。

根據Parent.children集合中的Parent對象和其他子項中的其他內容已更改/未更改,您可能會得到不同的結果。捕獲解釋計劃的SQL時,您會想嘗試不同的方案。