簡體   English   中英

ManyToOne HashCode和Equal實現

[英]ManyToOne HashCode & Equal implementation

我有三個這樣的實體:

1.項目:

@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.用戶:

@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,合作者

@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&equals應該如何實現?

原因是當我使用Eclipse自動生成它們時,出現了StackOverFlow Error並且這是一個永無止境的循環。

任何建議將不勝感激,謝謝。

起初,對不起我的英語不好,但是我相信您的錯誤是將所有字段都放在了equals和hashCode方法中。 您必須僅放置“普通”字段,而不是列表和集合。

請嘗試執行此操作,並在解決問題后再回答。

您應該使用“業務鍵相等”實現equalshashcode

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

在您的情況下,您僅應使用字段id

當Eclipse生成hashcodeequals方法時,可以選擇此字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM