在JPA中避免添加重复的数据与多对多关系,可以使用以下几种解决方法:
@Entity
public class EntityA {
// ...
@ManyToMany
private Set entityBs = new HashSet<>();
// ...
}
@Entity
public class EntityA {
// ...
@ManyToMany
private List entityBs = new ArrayList<>();
// ...
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EntityA entityA = (EntityA) o;
return Objects.equals(id, entityA.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
@Entity
public class EntityA {
// ...
@ManyToMany
@JoinTable(name = "table_name", uniqueConstraints = @UniqueConstraint(columnNames = {"entitya_id", "entityb_id"}))
private List entityBs = new ArrayList<>();
// ...
}
以上是几种常用的解决方法,根据具体情况选择适合的方法来避免在JPA中添加重复的数据与多对多关系。
上一篇:避免在JPA中初始化空的子集合