Java 更新对象级联关系复制子对象时的Spring数据
我正在使用带有jpa注释的Spring数据创建一个应用程序 我在问题和选择之间定义了一个多对多关系,所以我有一个问题选择对象来将多对多关系一分为二 我试图做到的是,当一个问题被保存时,所有相关的选择都会随问题一起保存/更新 这是我目前的代码:Java 更新对象级联关系复制子对象时的Spring数据,java,hibernate,jpa,spring-data,Java,Hibernate,Jpa,Spring Data,我正在使用带有jpa注释的Spring数据创建一个应用程序 我在问题和选择之间定义了一个多对多关系,所以我有一个问题选择对象来将多对多关系一分为二 我试图做到的是,当一个问题被保存时,所有相关的选择都会随问题一起保存/更新 这是我目前的代码: @Entity @Table(name = "question") public class Question { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Co
@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> {
}
任何解释都将不胜感激。try-testQuestion=dao.getQuestionRepo().save(testQuestion);-该引用可能未被更新try-testQuestion=dao.getQuestionRepo().save(testQuestion);-引用可能没有被更新
@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());
}