[英]toBuilder() vs Setter in database
I am trying to save data in database with OneToOne mapping in bidirectional way.我正在尝试以双向方式使用 OneToOne 映射将数据保存在数据库中。 I have used toBuilder and setter and got different result in Database.我用过 toBuilder 和 setter 并在数据库中得到了不同的结果。 By using setter:通过使用设置器:
Question question = Question.builder().quest("What is Pythonn ?").answer(null).build();
Answer answer = Answer.builder().answer("Python is language").que(question).build();
answer.setQue(question);
question.setAnswer(answer);
Question question2 = Question.builder().quest("How are you ?").answer(null).build();
Answer answer2 = Answer.builder().answer("I am fine").build();
answer2.setQue(question2);
question2.setAnswer(answer2);
session.save(question);
session.save(question2);
the result in db数据库中的结果
By using toBuilder通过使用 toBuilder
answer.toBuilder().que(question).build();
question = question.toBuilder().answer(answer).build();
answer2.toBuilder().que(question2).build();
question2 = question.toBuilder().answer(answer2).build();
The result in db: question_table db 中的结果: question_table
Why toBuilder is not working while setter is working ?为什么在 setter 工作时 toBuilder 不工作?
You don't save a reference to question2 in answer2.您不会在 answer2 中保存对 question2 的引用。 That's why answer 2 has a null value for the question column.这就是为什么答案 2 的问题列具有空值。
Answer answer2 = Answer.builder().answer("I am fine").build();
answer2.toBuilder().que(question2).build();
And you use question in the builder for question2.并且您在问题 2 的构建器中使用问题。 That's why there are multiple entries for question 1.这就是问题 1 有多个条目的原因。
question2 = question.toBuilder().answer(answer2).build();
As for first question row with a null value for answer, I'm not sure where that's coming from.至于答案为空值的第一个问题行,我不确定它来自哪里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.