Hibernate保存/更新/删除OneToMany关系

时间:2018-02-22 09:59:09

标签: java spring hibernate hibernate-mapping hibernate-5.x

我在下面的Hibernate实体中有 OneToMany 关系:

表单实体:

@Entity
@Table(name = "form_master")
public class Form {

    private long id;
    private String name;
    private List<Question> questions;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

  @Column(name = "name", nullable = false)
  public String getName() {
     return name;
  }

  public void setName(final String name) {
     this.name = name;
  }


    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(mappedBy = "form", cascade = CascadeType.ALL, orphanRemoval = true)
    public List<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }
}

问题实体:

@Entity
@Table(name = "question")
public class Question {

    private long id;
    private Form form;
    private String text;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @ManyToOne
    @JoinColumn(name = "form_id", nullable = true)
    public Form getForm() {
        return form;
    }

    public void setForm(Form form) {
        this.form = form;
    }
}

现在我按照以下方式保存新的表单 json:

{"name":"Test Form", "questions" : [{"text" : "Question 1"}, {"text" : "Question 2"}]}}

所以它创建了一个新表单和2个新问题。但是在编辑时,如果用户删除问题2并添加新问题3并发送如下的json:

{"id" : 1, "name":"Test Form", "questions" : [{"id" : 2, "text" : "Question 1"}, {"text" : "Question 3"}]}}

然后问题2不是从DB中删除而问题3是作为新问题添加的。

所以,我需要帮助为什么这个问题2没有删除?

我正在使用整个表单的saveOrUpdate,从JSON转换而来。

getSessionFactory().getCurrentSession().saveOrUpdate(form);

0 个答案:

没有答案