9

Let's say I have the following scenario:

@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?
}

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

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

Alfredo Osorio
  • 11,297
  • 12
  • 56
  • 84
  • are you sure "name" is going to be truly unique? Not hard to imagine a situation where two people have the same name. – matt b Jan 21 '11 at 18:54
  • 1
    It was just an example. Not a real scenario. – Alfredo Osorio Jan 21 '11 at 19:24
  • Just a note... Your *Person* class ain't *final*. You should realize that if you extend *Person* your *equals* is broken because, as Joshua Bloch puts it in *"Effective Java"* : **there is simply no way to extend an instantiable class while preserving the equals contract**. I don't know when *"Effective Java"* came out (2001?), but I'm sure one day people will admit that having *equals()* and *hashCode()* at the top of the Java OO-hierarchy was one of Gosling's biggest brain fart ;) [that OO problem was known before that but *Effective Java* tends to be authoritative] – SyntaxT3rr0r Jan 21 '11 at 19:44
  • 3
    An entity class must not be final according to JPA Spec. – Alfredo Osorio Jan 21 '11 at 21:54

1 Answers1

6

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.

Karthik Ramachandran
  • 11,925
  • 10
  • 45
  • 53