无法将一对多关系对象保存到数据库中。如何保存 table 列表?
Unable to save one-to-many relationship objects in to database. How to save a table list?
问题table:
public class Question {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column
@NotNull
private String questionSentence;
@OneToMany(mappedBy = "question",cascade = CascadeType.REMOVE)
private List<Answers> answers;
}
回答table:
public class Answers {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
@NotNull
private String answer;
@ManyToOne
@JoinColumn
@JsonIgnore
private Question question;
}
我想在从 RequestBody 收到的问题中保存一个答案列表,但它不起作用:
public class QuestionService {
@Autowired
private QuestionRepository questionRepository;
public ResponseEntity<Question> update
(Integer questionId,
Question question) {
Question tempquestion = = questionRepository.findById(questionId);
tempquestion.setAnswers(Question.getAnswers());
return ResponseEntity.ok(questionRepository.save(tempQuestion));
}
tempQuestion 输出有效(我从所有答案中得到一个列表),但“questionRepository.save(tempQuestion)”没有保存它。 (如果我想保存其他东西,比如字符串答案句等,它可以工作,但如果我想保存 table 列表。
我做错了什么?
如果在保存Question
实体的时候需要级联保存操作,那么在Question
和[=16]的关系上使用CascadeType.PERSIST
和CascadeType.MERGE
=] 实体:
@OneToMany(mappedBy = "question",cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List<Answers> answers;
}
或者如果您想将 Question
上的所有操作级联到 Answer
实体,则使用:
@OneToMany(mappedBy = "question",cascade = CascadeType.ALL)
private List<Answers> answers;
}
问题table:
public class Question {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column
@NotNull
private String questionSentence;
@OneToMany(mappedBy = "question",cascade = CascadeType.REMOVE)
private List<Answers> answers;
}
回答table:
public class Answers {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
@NotNull
private String answer;
@ManyToOne
@JoinColumn
@JsonIgnore
private Question question;
}
我想在从 RequestBody 收到的问题中保存一个答案列表,但它不起作用:
public class QuestionService {
@Autowired
private QuestionRepository questionRepository;
public ResponseEntity<Question> update
(Integer questionId,
Question question) {
Question tempquestion = = questionRepository.findById(questionId);
tempquestion.setAnswers(Question.getAnswers());
return ResponseEntity.ok(questionRepository.save(tempQuestion));
}
tempQuestion 输出有效(我从所有答案中得到一个列表),但“questionRepository.save(tempQuestion)”没有保存它。 (如果我想保存其他东西,比如字符串答案句等,它可以工作,但如果我想保存 table 列表。
我做错了什么?
如果在保存Question
实体的时候需要级联保存操作,那么在Question
和[=16]的关系上使用CascadeType.PERSIST
和CascadeType.MERGE
=] 实体:
@OneToMany(mappedBy = "question",cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List<Answers> answers;
}
或者如果您想将 Question
上的所有操作级联到 Answer
实体,则使用:
@OneToMany(mappedBy = "question",cascade = CascadeType.ALL)
private List<Answers> answers;
}