开发者社区> 问答> 正文

jpa 中的CascadeType.Merge

关于配置一对多的多端的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框架本人是初学者,,烦请指教,谢谢

(为了突出问题,删掉了不必要的代码,见谅)

展开
收起
爵霸 2016-03-04 09:18:51 2575 0
1 条回答
写回答
取消 提交回答
  • 你要级联保存的话得双向配置。

    2019-07-17 18:51:48
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载