我正在使用带有jpa注释的Spring-Data创建一个应用程序。
我在Question和Choice之间定义了多对多的关系,所以我有一个QuestionChoice对象来打破两个中的多对多关系。
我想要完成的是,在保存问题时,所有相关选项都会随问题一起保存/更新。
到目前为止,这是我的代码:
@Entity
@Table(name = "question")
public class Question {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID")
private long id;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "question",
cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Set<QuestionChoice> questionChoices;
…
}
@Entity
@Table(name="question_choice")
public class QuestionChoice {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@ManyToOne
@JoinColumn(name="questionId", referencedColumnName="id")
private Question question;
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name="choiceId", referencedColumnName="id")
private Choice choice;
…
}
@Entity
@Table(name = "CHOICE")
public class Choice {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID")
private long id;
@OneToMany(mappedBy = "choice")
private List<QuestionChoice> questions;
…
}
@Repository
public interface QuestionRepository extends JpaRepository<Question,Long> {
}
代码工作得很好。当我创建一个新对象时,会正确创建Question,Question_Choice和Choice表记录。
问题是当我在保存Question对象后尝试添加新的Chocie时...存储库再次插入所有选项,而不是仅插入新添加的选项......
在下面的JUnit示例中,最后一个assertEquals告诉我有3个孩子而不是2个孩子:
@Test
public void TestSaveQuestionAndAddChoices(){
Question testQuestion = new Question();
testQuestion.setDescription("Test");
testQuestion.setClarification("Test Clarification");
testQuestion.setAnswerExplanation("Test Answer");
testQuestion.setLinkForAdditionalInformation("https://link5.com");
testQuestion.setPoints(7);
testQuestion.setTimeToAnswer(100);
/** Check if the Question Id is correct Changed by the Save Method */
Assert.assertEquals(0, testQuestion.getId());
dao.getQuestionRepo().save(testQuestion);
Assert.assertNotEquals(0, testQuestion.getId());
/** Check Adding a Choice after the Question was saved & save*/
Choice choice1 = new Choice("Test - Choice 1");
testQuestion.addChoice(choice1, false);
dao.getQuestionRepo().save(testQuestion);
/* Retrieve the Question and verify the Size of the Array */
Question retrievedQuestion = dao.getQuestionRepo().findOne(testQuestion.getId());
Assert.assertEquals(1, retrievedQuestion.getQuestionChoices().size());
/** Check Adding a Second Choice and save */
testQuestion.addChoice(new Choice("Test - Choice 2"), false);
dao.getQuestionRepo().save(testQuestion);
Question retrievedQuestion2 = dao.getQuestionRepo().findOne(testQuestion.getId());
Assert.assertEquals(2, retrievedQuestion2.getQuestionChoices().size());
}
任何解释都会得到很大的解释。