ManyToOne HashCode&平等实施

时间:2016-10-11 15:20:13

标签: java sql eclipse hibernate jpa

我有三个这样的实体:

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
}

hashCode&amp;等于是否需要实施?

因为当我使用Eclipse自动生成它时,我得到一个StackOverFlow Error并且它是一个永无止境的循环。

任何建议都将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:-1)

首先,抱歉我的英语不好,但我相信你的错误是将所有字段放在方法等于和hashCode。您必须只放置“普通”字段,而不是列表和集合。

请尝试这样做,并在回答后解决了这个问题。

答案 1 :(得分:-1)

您应该使用“商家密钥相等”

来实施equalshashcode

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

在您的情况下,您应该只使用字段id

当Eclipse生成hashcodeequals方法时,您可以选择此字段。