我有一个Entity,它在一个集合中包含另一个Entity,它本身包含一个相同类的实体的集合,就像这样:
@Entity
@Table(name="parents")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(cascade = CascadeType.ALL)
private Set<Task> tasks;
public Parent() {}
public Parent(Set<Task> tasks) {
this.tasks = tasks;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<Task> getTasks() {
return tasks;
}
public void setTasks(Set<Task> tasks) {
this.tasks = tasks;
}
@Entity
@Table(name="tasks")
public static class Task {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "task_id")
private long id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
private Set<Task> dependencies;
public Task() {}
public Task(String name) {
this.name = name;
dependencies = new LinkedHashSet<>();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Task> getDependencies() {
return dependencies;
}
public void setDependencies(Set<Task> dependencies) {
this.dependencies = dependencies;
}
}
}
我的问题是两个Task
可能在他们的Task
中引用相同的dependencies
,因此当我尝试保存Parent
时, org.hibernate.exception.ConstraintViolationException: could not execute statement
,SQL表示:Duplicate entry '12' for key 'UK_q8xuxyx9iylvc9ddh8fudtlsf'
我该如何克服这个问题?任何帮助表示赞赏。