What is the correct way of overriding hashCode () and equals () methods of persistent entity?

后端 未结 7 2058
青春惊慌失措
青春惊慌失措 2020-12-14 10:28

I have a simple class Role:

@Entity
@Table (name = \"ROLE\")
public class Role implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;         


        
相关标签:
7条回答
  • 2020-12-14 10:47

    The business key of an object may require its parent (or another one-to-one or many-to-one) relation. In those cases, calling equals() or hashcode() could result in a database hit. Aside from performance, if the session is closed that will cause an error. I mostly gave up trying to use business keys; I use the primary id and avoid using un-saved entities in maps and sets. Has worked well so far but it probably depends on the app (watch out when saving multiple children through the parent cascade). Occasionally, I'll use a separate meaningless key field that's a uuid auto-generated in the constructor or by the object creator.

    0 讨论(0)
提交回复
热议问题