After reading several articles, threads and making some research, now I am completely confused regarding to implementing a proper equals and hashCode method in my Spring Boot app.
For example, I have the following class:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
@Column(length = 100)
private String description;
@Column(nullable = false)
private Integer prepTime;
@Column(nullable = false)
private Integer cookTime;
@Column(nullable = false)
private Integer servings;
@Lob
@org.hibernate.annotations.Type(type = "org.hibernate.type.TextType")
@Column(nullable = false)
private String instructions;
@Column(nullable = false)
@Enumerated(value = EnumType.STRING)
private Difficulty difficulty;
@Column(nullable = false)
@Enumerated(value = EnumType.STRING)
private HealthLabel healthLabel;
@ManyToOne(optional = true, fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", referencedColumnName = "id")
private Category category;
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RecipeIngredient> recipeIngredients = new ArrayList<>();
}
I have trouble for these issues below and trying to implement equals and hashCode methods properly:
1) As far as I know, when there is a unique field that can be used to differentiate one person from the other e.g. email or username, then it is enough ONLY use these fields in equals and hashCode method. Is that true?
2) If there is not any unique field except from id, then should I add ALL the fields (id and the others) to equals and hashCode method implementation?
3) When using Hibernate and Data JPA, should I follow a different approach than other situation as there are 4 states transient, managed, removed, and detached in JPA lifecycle? I think id field should not be used in this situation as it is not present in transient mode? Right?
CodePudding user response:
When implementing equals() and hashCode() methods:
If there is a unique field that can be used to differentiate one object from another, use only that field in the implementation.
If there is no unique field, use all the fields including the id in the implementation.
When using Hibernate and Data JPA, do not use the ID field in the implementation as it is not present in the transient state, instead use fields that are present in all states such as unique fields or all fields.
CodePudding user response:
as you are already using lombok, you can use @Data
annotation as well:
@Data All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor!