qq_27356173
qq_27356173
2016-05-17 03:19

关于hibernate单向一对多的一个问题

一个学生一个班级,班级一对多学生,班级中有一个Set里面存放学生,我执行下面的代码

 @Test
    public void testUpdateStuToNewClass(){
        Session session = factory.openSession();
        Transaction transaction = session.beginTransaction();
        Student stu = session.get(Student.class, 2L);
        Classes clazz = new Classes();
        clazz.setCname("2班");
        Set<Student> students = new HashSet<Student>();
        students.add(stu);
        clazz.setStudents(students);
        transaction.commit();
        session.close();
    }

我并没有session.save(classes),但是为什么会执行insert和update呢,classes不是临时状态的么 hibernate生成的sql如下

 Hibernate: 
    select
        student0_.pid as pid1_1_0_,
        student0_.pname as pname2_1_0_,
        student0_.description as descript3_1_0_ 
    from
        Student student0_ 
    where
        student0_.pid=?
Hibernate: 
    select
        max(cid) 
    from
        Classes
Hibernate: 
    insert 
    into
        Classes
        (cname, cid) 
    values
        (?, ?)
Hibernate: 
    update
        Student 
    set
        cid=? 
    where
        pid=?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换