尝试保存实体时输入重复

时间:2019-07-11 13:55:39

标签: jpa spring-data-jpa spring-data

我有一个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'

我该如何克服这个问题?任何帮助表示赞赏。

0 个答案:

没有答案