奖励实体
@JsonIgnore
@ManyToMany(mappedBy="awards", fetch=FetchType.LAZY)
private Set<Winner> winners = new HashSet<>();
获胜者实体
@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="AWARD_ASSIGNMENT",
joinColumns={@JoinColumn(name="WINNER_ID", referencedColumnName="ID")},
inverseJoinColumns={@JoinColumn(name="AWARD_ID", referencedColumnName="ID")})
private Set<Award> awards = new HashSet<>();
我正在调用这个hibernate fetch方法
return getSession().createQuery("from Winner").list();
Hashcode等于奖励实体中的方法覆盖
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((winners == null) ? 0 : winners.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Award other = (Award) obj;
if (id != other.id)
return false;
if (winners == null) {
if (other.winners != null)
return false;
} else if (!winners.equals(other.winners))
return false;
return true;
}
获胜者实体
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((awards == null) ? 0 : awards.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Winner other = (Winner) obj;
if (awards == null) {
if (other.awards != null)
return false;
} else if (!awards.equals(other.awards))
return false;
if (id != other.id)
return false;
return true;
}
覆盖equals和hashcode方法,因为多对多关系使用SET。
答案 0 :(得分:0)
要记住的要点:
1)确保哈希码或相同方法中没有关联(一对多/多对多..等)。覆盖hashcode / equals方法时,使用使该对象唯一的字段(例如,FirstName + LastName +电话号码)尽量避免使用JPA生成的PK Id。
2)限制Jackson / Json序列化以避免深度遍历。
@JsonManagedReference
private Set<Award> awards = new HashSet<>();
@JsonBackReference
private Set<Winner> winners = new HashSet<>();