Object equality in context of hibernate / webapp

后端 未结 5 629
孤城傲影
孤城傲影 2020-12-08 22:46

How do you handle object equality for java objects managed by hibernate? In the \'hibernate in action\' book they say that one should favor business keys over surrogate keys

5条回答
  •  醉梦人生
    2020-12-08 23:13

    The question is how often are you likely to have multiple unsaved objects that might be duplicates that need to go into a set or map? For me, the answer is virtually never so I use surrogate keys and super.equals/hashcode for unsaved objects.

    Business keys make sense in some cases, but they can cause problems. For example, what if two people live at the same address - if you want that to be one record in the database, then you have to manage it as a many-to-many and lose the ability to cascade delete it so when the last person living there is deleted, you have to do extra work to get rid of the address. But if you store the same addresss for each person then your business key has to include the person entity, which may mean a database hit inside your equals/hashcode methods.

提交回复
热议问题