Should I write equals() and hashCode() methods in JPA entities?

后端 未结 6 1870
说谎
说谎 2020-11-28 19:35

I want to check if entity is in a Collection member (@OneToMany or @ManyToMany) of another entity:

if (entity2.getEntities1().conta         


        
6条回答
  •  Happy的楠姐
    2020-11-28 20:24

    Yes, you should!

    If you don't override the default Java.lang.Object equals and hashCode implementation:

    @Entity(name = "Book")
    public class Book implements Identifiable {
     
        @Id
        @GeneratedValue
        private Long id;
     
        private String title;
     
        //Getters and setters omitted for brevity
    }
    

    the merge operation will return a different object instance and the equality contract is going to be broken as explain in this post.

    The best way is to use a business key, like this:

    @Entity
    public class Book implements Identifiable {
     
        @Id
        @GeneratedValue
        private Long id;
     
        private String title;
     
        @NaturalId
        private String isbn;
     
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Book)) return false;
            Book book = (Book) o;
            return Objects.equals(getIsbn(), book.getIsbn());
        }
     
        @Override
        public int hashCode() {
            return Objects.hash(getIsbn());
        }
     
        //Getters and setters omitted for brevity
    }
    

    You can also use the identifier for equality, but mind that the hashCode implementation should always return the same value as explained in the same post that I already mentioned:

    @Entity
    public class Book implements Identifiable {
     
        @Id
        @GeneratedValue
        private Long id;
     
        private String title;
     
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Book)) return false;
            Book book = (Book) o;
            return Objects.equals(getId(), book.getId());
        }
     
        @Override
        public int hashCode() {
            return getClass().hashCode();
        }
     
        //Getters and setters omitted for brevity
    }
    

提交回复
热议问题