簡體   English   中英

什么時候在Hibernate下需要Hashcode和Equals實現?

[英]when Hashcode and Equals implementation is required under hibernate?

每個鏈接

要點是,如果您的實體將成為Set(條件1)的一部分或/並且如果您要分離/附加其實例,則只需擔心它。(condition2)

根據我的理解,我們僅需要條件1,其中要求哈希碼和equals方法實現

如果我有一個我不想存儲重復客戶(基於客戶名稱)或不想從休眠api檢索重復客戶(用於遺留數據)的需求,那么我的理解是在設置條件下存儲客戶確實很有意義,這就是僅在需要實現哈希碼和equals方法的情況下。

我不明白當我們將要分離/附加它的instance(condition)時,hashcode和等價實現如何提供幫助

更新:-確認我嘗試重新附加分離的實例,如下所示

   person detached instance lying here for id 1// person overrides hashcode and equals method

   session = factory.openSession();
   tx = session.beginTransaction();
   person1=(Person)session.get(Person.class, 1);
   session.lock(person, LockMode.NONE);// reattaching the detached instance here
   // as per Marko Topolnik  comment i was expecting equality will be checked based on equals and hashcode 
   // method but it was done based on person id . so question is  does hashcode and equals come into picture
   // while reattaching the detached instance


   tx.commit();

分離和附加依賴於@id。 不要依賴錯誤的答案,正確的答案是您提供的鏈接中第二個答案(由Phil撰寫)。

如果實體將在Set中使用(這是很常見的) 並且該實體將與休眠會話分離並隨后重新附加到休眠會話中,則只需要重寫equals()和hashcode()即可。休眠)。

正如hiberante文檔所述

  • 打算將持久類的實例放入Set中(表示多值關聯的推薦方式);
  • 打算使用附加的分離實例

這意味着如果您打算在父實體中重新附加存儲在Set中的實體。 因此,只有同時滿足兩個條件時 ,Hashnate才需要Hashcode和Equals實現。

另外,當您使用復合主鍵時,最好實現equals和hashCode,因為它是在復合id部分編寫的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM