[英]OneToMany deleting only one part of the relationship
因此,我有以下課程:
@Entity
@Table(name="tbStudent")
public class Student {
@OneToMany(mappedBy="student")
private List<Report> reports;
}
和
@Entity
@Table(name="tbReport")
public class Report {
@ManyToOne
@JoinColumn(name="student_fk", updatable=true, nullable=true)
private Student student;
}
我希望能夠刪除一名學生,但保留報告。
因此,有沒有辦法將報告中的學生FK更新為null,以便我可以毫無問題地刪除該學生?
我在HQL中創建了一個函數,每次嘗試刪除學生時,都會將FK更新為null,但它似乎不起作用。
這里是:
public void deleteStudentReport(Student student){
String id = student.getId();
EntityManager em = emf.createEntityManager();
Query q = em.createQuery("update Report r set r.student.id = null where r.student.id = :id");
q.setParameter("id", id);
}
編輯:
我在嘗試刪除學生時調用查詢:
@ManagedBean(name = "studentMB")
@ViewScoped
public class StudentMB {
public void delete(){
studentDao.deleteStudentReport(student);
studentDao.delete(student);
}
}
解:
感謝Naros的回復,我最終在Student類上設置了此方法:
@PreRemove
public void preRemove(){
for(Report r : reports){
d.setStudent(null);
}
}
基本上,您只需要在存儲庫/ dao類上或在服務層中需要報表實例並清除學生的業務功能即可。
public void clearReportStudent(Report report) {
if(report != null) {
Student student = report.getStudent();
if(student != null) {
student.getReports().remove(report);
report.setStudent(null);
}
}
}
我通常更喜歡將這些類型的輔助方法放在自己的域模型上,並根據需要從我的服務/業務邏輯中調用操作。
public class Report {
public void unlinkFromStudent() {
if(this.student != null) {
this.student.getReports().remove(this);
this.student = null;
}
}
}
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.