SpringBoot_JPA:OneToMany(双向)不在子表中插入外键

时间:2017-01-09 05:31:28

标签: hibernate jpa spring-boot spring-web

SpringBoot版本:1.4.2.RELEASE MySQL版本:5.7.16 Lombok的

我有两个实体类问题和选项,其中Question表中的question_id是Question_Option表中的外键。

问题实体

@Entity
@Table(name = "questions")
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
@Setter
private int questionId;
@Getter
@Setter
@OneToMany(mappedBy = "question",fetch=FetchType.LAZY,   cascade=CascadeType.ALL)
private List<Option> option;

选项实体

@Entity
@Table(name = "questions_options")
public class Option {
@Id
@GeneratedValue
@Getter
@Setter
private int id;
@Getter
@Setter
private String optionsId;
@Getter
@Setter
 private String optionText;
@ManyToOne
@JoinColumn(name="questionId")
@Getter
@Setter
private Question question;
}

问题陈述 当我尝试POST时,外键(question_id)未插入选项表中。

Hibernate: insert into questions (questionId, LastUpdate, active, createTime, questionText, questionType) values (default, ?, ?, ?, ?, ?)
Hibernate: insert into questions_options (id, lastUpdate, optionText, optionsId, questionId) values (default, ?, ?, ?, ?)
Hibernate: insert into questions_options (id, lastUpdate, optionText, optionsId, questionId) values (default, ?, ?, ?, ?)

Hibernate:插入questions_options(id,lastUpdate,optionText,optionsId,questionId)值(默认值,?,?,?,?)

我是如何解决这个问题的? 我将Question实体改为

@Getter
@Setter
@OneToMany(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name="questionId")
@NotNull
private List<Option> option;

和选项

@ManyToOne
@Getter
@Setter
@JoinColumn(name="questionId")
private Question question;

但我想知道为什么第一种方法不起作用,我做错了什么。

2 个答案:

答案 0 :(得分:0)

尝试以下关系,它应该有效。

问题实体

@OneToMany(mappedBy = "question",fetch=FetchType.LAZY,cascade=CascadeType.ALL, targetEntity = Option.class)
private List<Option> option

选项实体

@ManyToOne
@JoinColumn(name = "questionId")
private Question question;

答案 1 :(得分:0)

这就是控制器类中的样子。

@PostMapping("/question")
public question addQuestion(@RequestBody Question question) {

    if( question.getOption().size() > 0 )
    {
        question.getOption().stream().forEach( option -> {
            option.setQuestion( question );
        } );
    }

   // You can save this question object now using the repository instance autowired.
    return question;
}

还有一件事情,在Option类实体中,您需要如下添加@JsonIgnore注释,以避免递归获取

@ManyToOne
@Getter
@Setter
@JoinColumn(name="questionId")
@JsonIgnore
private Question question;