Skip to content
Advertisement

Which choice is better for generating equals() and hashCode() methods in Hibernate?

I create equals() and hashCode() methods in each Hibernate entity (if there is no inheritance) in my Java app. However, I am a little bit confused and wanted to be sure if I define it properly. Could you please clarify the following issues?

  1. In IntelliJ, when I use the “Generate” feature (via Alt + Insert), there are some templates like IntelliJ Default, Java 7+, etc. Which template should I use?

  2. When using the “Generate” feature, which field should I include in my equals() and hashCode() methods of the following entity?

    @Entity
    public class User {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        private String name;
    
        @Column(unique = true)
        private String email;
    
        // getter, setter, constructor...
    }
    
  3. Should I use annotation for simple and easy usage like @EqualsAndHashCode? Or is it not flexible and should I prefer implementing explicitly?

Advertisement

Answer

Use the option that generates fewer code and no need 3rd party libraries. I prefer Java7+. Include just the primary key field because the important thing is to verify if 2 differents instances are representing the same row in database. There’s no need to verify if all field values are the same.

You can read more about here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement