在spring应用程序中创建对象时,我遇到了问题。我有三个类,它们相互依赖。我有三节课。
public class Examine {
private Integer examineId;
private String title;
@JsonManagedReference
private Set<Question> questions;
public Examine(Integer examineId, String title) {
this.examineId = examineId;
this.title = title;
this.questions = new HashSet<>();
}
}public class Question {
private Integer questionId;
private String description;
@JsonBackReference
private Examine examine;
@JsonManagedReference
private Set<Answer> answers;
public Question(Integer questionId, String description, Examine examine) {
this.questionId = questionId;
this.description = description;
this.examine = examine;
this.answers = new HashSet<>();
}
}public class Answer {
private Integer answerId;
private String answer;
@JsonBackReference
private Question question;
public Answer(Integer answerId, String answer) {
this.answerId = answerId;
this.answer = answer;
}
}我的问题是。我不太确定我应该按照什么顺序创建对象。下面列出了我的服务类。我开始从类创建对象,这是最外部的检查。
用于检查类的
public void createExamine(Examine examine) {
examineRepository.save(examine);
}examineId,然后将问题分配给特定的检查. public void createQuestion(Question question, Integer examineId) {
Examine examine = examineService.getExamine(examineId);
question.setExamine(examine);
questionRepository.save(question);
}questionId并为特定的问题分配答案。 public void createAnswer(Answer answer, Integer questionId) {
Question question = questionService.getQuestion(questionId);
answer.setQuestion(question);
answerRepository.save(answer);
}如果我想得对,你能帮我/告诉我吗?至于检查类,我很肯定它是可以的-我对另外两个类有疑问-如果创建它们和相互链接的方法是正确的。
发布于 2020-06-28 17:06:11
在JPA中,In由ORM层生成。
您必须定义这样的实体:
@Entity
@Table(name = "EXAMINE")
public class Examine implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;然后按照映射规则对其他实体进行分析。
创建对象的顺序并不重要,要链接对象,至少需要链接两个对象。所以examine.setQuestion(问题)。
其他物体上也是一样的。
最后,保存域层次结构的顶层对象。EntityManager.save(检查);
看一看这样的事物:
https://stackoverflow.com/questions/62625598
复制相似问题