Moatez Bouhdid Moatez Bouhdid - 1 month ago 14
SQL Question

ManyToOne HashCode & Equal implementation

I have three entities like this :

1.Project :

@Entity
public class Project implements Serializable{

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", unique=true )
private Long id;

@OneToMany(mappedBy="project", fetch = FetchType.EAGER)
private Set<Collaborator> collaborators = new HashSet<>();

//Getters & Setters


}

2.User :

@Entity
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private Long id;

@OneToMany(mappedBy="user", fetch = FetchType.EAGER)
private Set<Collaborator> collaborators = new HashSet<>();

//Getters & Setters
}


3.Collaborator :

@Entity
public class Collaborator implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ProjectID" , nullable = true)
private Project project;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "UserID", nullable = true)
private User user;

//Getters & Setters
}


How should hashCode & equals needs to be implemented ?

Cause when I generate them automatically with Eclipse I get a
StackOverFlow Error
And it's a never ending loop.

Any suggestion would be appreciated, Thank you.

Answer

You should implement your equals and hashcode using "Business key equality"

https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html

In your case, you should only use the field id.

You may select this field when Eclipse is generating the hashcode and equals methods.