可嵌入的jpa类应该实现equals和hashCode吗? [英] Should embeddable jpa class implement equals and hashCode?

查看:113
本文介绍了可嵌入的jpa类应该实现equals和hashCode吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下情况:

@Entity
public class Person {
    @Id
    private Long id; //Surrogate key

    @Embedded
    private Name name; //Natural key

    public int hashCode() {
        ... //based on natural key Name
    }
    public boolean equals(Object obj) {
        ... //based on natural key Name
    }
}

@Embeddable
public class Name {
    private String firstName;
    private String middleName;
    private String lastName;

    //Should I implement equals/hashCode baseed on the three fields?
}

为了让Person equals正常工作,Name类应该在Name类上实现equals和hashCode吗?

Should Name class implement equals and hashCode on Name class in order that Person equals work properly?.

对于将用作EmbeddedId的Embeddable对象是必须的.但是在此示例中,我使用代理键.

For an Embeddable object that will be used as an EmbeddedId is a must. But in this example I'm using surrogate key.

推荐答案

我不相信JPA曾经要求您实现equals和hashcode. Hibernate曾经使用过,但是最近对文档的评论显示,这不再是必需的.

I don't believe JPA ever requires you to implement equals and hashcode. Hibernate used to, but a recent review of the docs shows that this is no longer a requirement.

但是,当然,实现哈希码和等于总是一个好主意.

But of course it's always a good idea to implement hashcode and equals.

这篇关于可嵌入的jpa类应该实现equals和hashCode吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆