我有两个实体,分别是 ExmStudentMarksEntry 和 ExmStudentMarksEntrySubcat
请查看实体
父级 ExmStudentMarksEntry
@Entity
@Table(name = "exm_student_marks_entry")
public class ExmStudentMarksEntry implements java.io.Serializable {
private Integer studentMarksId;
private String marks;
private Set<ExmStudentMarksEntrySubcat> exmStudentMarksEntrySubcats = new HashSet<ExmStudentMarksEntrySubcat>(0);
@OneToMany(fetch = FetchType.LAZY, mappedBy = "exmStudentMarksEntry",cascade=CascadeType.ALL)
public Set<ExmStudentMarksEntrySubcat> getExmStudentMarksEntrySubcats() {
return this.exmStudentMarksEntrySubcats;
}
public void setExmStudentMarksEntrySubcats(Set<ExmStudentMarksEntrySubcat> exmStudentMarksEntrySubcats) {
this.exmStudentMarksEntrySubcats = exmStudentMarksEntrySubcats;
}
}
和子实体 ExmStudentMarksEntrySubcat
@Entity
@Table(name = "exm_student_marks_entry_subcat")
public class ExmStudentMarksEntrySubcat implements java.io.Serializable {
private Integer studentMarksSubcatId;
private ExmStudentMarksEntry exmStudentMarksEntry;
private String marks;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "student_marks_id", nullable = false)
public ExmStudentMarksEntry getExmStudentMarksEntry() {
return this.exmStudentMarksEntry;
}
public void setExmStudentMarksEntry(ExmStudentMarksEntry exmStudentMarksEntry) {
this.exmStudentMarksEntry = exmStudentMarksEntry;
}
}
我想使用休眠CascadeType来保存父级和子级实体 因此,我尝试通过在父类中为孩子提供 CascadeType.All ,但是它对我不起作用。
我将子对象设置为父对象并保存如下
@Override
public boolean addExamMarks(ExmStudentMarksEntry esm) {
// TODO Auto-generated method stub
boolean success = false;
try {
currentSession=sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(esm);
success=true;
}
catch (Exception e) {
e.printStackTrace();
}
return success;
}
}
int仅插入父对象,而不插入childs。给出以下异常
org.hibernate.PropertyValueException: not-null property references a null or transient value : com.rasvek.cg.entity.ExmStudentMarksEntrySubcat.exmStudentMarksEntry
请帮帮我。如何使用休眠模式实现这一目标?
谢谢。
答案 0 :(得分:0)
级联操作仅在更新或删除对象时发生,而不在添加时发生。要添加,您必须手动设置对象。例如:
try {
currentSession=sessionFactory.getCurrentSession();
for(ExmStudentMarksEntrySubcat subcat : esm.getExmStudentMarksEntrySubcats()) {
subcat.setExmStudentMarksEntry(esm);
}
currentSession.saveOrUpdate(esm);
success=true;
}