我想更新一個事務內的實體,首先我選擇使用它的主鍵的實體,然後懶惰地加載它的子實體並通過setter方法對其屬性進行更改。之後,當我合併父對象,自動其所有的子對象與OneToMany關係得到更新。雖然這是必需的功能,但我對這種行爲有點困惑,因爲我沒有爲子實體指定任何級聯選項。爲了確保,我甚至嘗試了一個非關係表,只是使用查找JPAQL來查詢並更改了它的屬性。當主實體合併操作之後提交事務時,此非關係實體也會與其他人一起更新。我不確定這是正確的行爲,還是它理解JPA和交易內合併操作的問題。JPA被管實體合併操作沒有級聯選項
我父類
class Student
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Integer id;
private String name;
@OneToMany(mappedBy = "student")
private List<Subjects> subjects;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
我的孩子類
Class Subjects
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Integer id;
@JoinColumn(name = "student", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Student student;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id=id;
}
public String getCourse(){
return course;
}
public void setCourse(String course){
this.course=course;
}
非關聯實體僅僅是沒有這個選擇的實體類的任何關係的實體類。我添加它來檢查更新是否由於實體類中指定的任何關係而發生(即使沒有級聯選項)。
我的交易更新功能。
Object obj1 = this.transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
Category category=findById('2'); //Non-Related entity with Student or Subject
category.setName('new category');
Student student=findStudentById(1);
for(Subjects subjects:student.getSubjects()){
subjects.setCourse("test");
}
student.setName("student1");
entityManager.merge(student);
return true;
}
});
所以合併和事務提交後的最終結果是,所有表(學生,主題和類別)更新。
發佈代碼而不是描述它。並定義一個非關係表是什麼。 –
@JBNizet,感謝您的回覆,我還添加了相關代碼。 – Krishna