关于配置一对多的多端的cascadetype的问题。
//学生类
public class Student{
private String s_id;
private ClassRoom classRoom;
//....getter and setter
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.MERGE)
@JoinColumn(name="c_id")
public Class getClassRoom() { return classRoom;}
}
//教室类
public class ClassRoom{
private String c_id;
pricate Set<Student> students = new HashSet<Studnet>(0);
//...getter and setter
}
//测试类
public class Test{
public void test(){
//新建一个教室对象
ClassRoom cr = new ClassRomm();
cr.setC_id("1");
//新建一个学生对象并且关联教室
Student stu = new Student();
stu.setS_id("201501");
stu.setClassRoom(cr);
//调用JPA的persistent方法
entityManager.persistent(stu);
}
}
//异常信息
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: ClassRoom -> ClassRoom
at org.hibernate.engine.CascadingAction$9.noCascade(CascadingAction.java:387)
at org.hibernate.engine.Cascade.cascade(Cascade.java:172)
at org.hibernate.event.def.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:154)
at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:145)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:88)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
... 36 more
我想为什么要在保存Student之前要先persistentClassRoom,我不是设置了CascadeType.MERGE了么。。。。原以为这里的MERGE和Hibernate的saveOrUpdate是一个意思,难道不是麼,,对于ORM框架本人是初学者,,烦请指教,谢谢
(为了突出问题,删掉了不必要的代码,见谅)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。