Do I need to implement equals() and hashCode() for entities in a @ManyToMany associations with an extra column

I have created a Many to Many to association with an extra column following this article. It shows and exmaple with following entites: Post, Tag, PostTag and embeddable PostTagId. Everything works fine, but I have two questions (general, not strictly related to given tutorial):


1. Article clearly states:

The @Embeddable type must override the default equals and hashCode methods based on the two Primary Key identifier values.

fine, but it narrows to the first question:
Considering (from doc - can’t put link as don’t have enough reputation, sorry) that I will NOT:

  • intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations) and
  • intend to use reattachment of detached instances

do I have to provide equals()/hashCode() for related entites as well ? (in this example it would be for Post and Tag ?)


2. Quoted doc clearly uses AND. It concern me as I though that using a collection on persistent class is enough alone to be “forced” to implement proper equals() and hashCode() isn’t it ? I was thinking about disjunction more than conjuction f.e. because the following test (from Why You Should Care About Equals and Hashcode - DZone) fails:

def "should find cart for given customer after correcting email address"() {
    given:
        Cart sampleCart = new Cart()
        Customer sampleCustomer = new Customer()
        sampleCustomer.setId(UUID.randomUUID())
        sampleCustomer.setEmail("emaill@customer.com")
        HashMap customerToCart = new HashMap<>()
    when:
        customerToCart.put(sampleCustomer, sampleCart)
    then:
        customerToCart.get(sampleCustomer) == sampleCart
    and:
        sampleCustomer.setEmail("email@customer.com")
        customerToCart.get(sampleCustomer) == sampleCart
}

If you map the PostTag entity, then implementing equals and hashCode for the parent entities is only needed if you store the entities in HashSets or HashMaps.

If you map the PostTag entity, then implementing equals and hashCode for the parent entities is only needed if you store the entities in HashSets or HashMaps.

why only HashMap and HashSet ? why it doesn’t apply to all collections from Java Collection framework ? So If I had a User entity with field List<Post> userPosts = new ArrayList<>(); then equals()/hashCode() isn’t necessary in parent entity ?

For Lists, unless you call contains or try to get the index of an element based on equals, it’s not needed to implement equals and hasCode.

However, this is not something needed by Hibernate, but by your business requirements. Hence, you are the only one who can answer whether you need it or not.

1 Like