OneToMany Hibernate保存级联问题

时间:2014-07-16 02:27:51

标签: java mysql database hibernate hibernate-onetomany

我正在使用Hibernate和OneToMany Relationship,我今天遇到了一个奇怪的行为, 虽然我故意这样做但我并没有期待这种行为

College.java

@Entity
@Table(name="COLLEGE")
public class College implements Serializable{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="COLLEGE_XID")
    private Long collegeId;

    @Column(name="COLLEGE_NAME")
    private String collegeName;

    @OneToMany(mappedBy="college",cascade = CascadeType.ALL) 
    private List<Student> studentList = new ArrayList<Student>();
    //... with get and setters
}

Student.java

@Entity
@Table(name = "STUDENT")
public class Student implements Serializable    {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="STUDENT_XID")
    private Long studentId;

    @Column(name="STUDENT_NAME")
    private String studentName;

    @ManyToOne
    @JoinColumn(name="COLLEGE_XID",nullable=false)
    private College college;
    //... with get and setters
}

Application.java

    College college1 = new BdCollege();
    college1.setCollegeName("C_1");

    College college2 = new BdCollege();
    college2.setCollegeName("C_2");

    Student student1 = new BdStudent();
    student1.setStudentName("S_1_C_2");

    CollegeDAO collegeDAO = new  CollegeDAO();

    // setting student 1 Parent to College 1        
    student1.setCollege(college1);   // <---- Here the Issue  ... student 1 as college 1 child

    // BUT assigning Student 1 as Child of Collge 2 in List 
    // i did it purposely to test the behaviour
    college2.getStudentList().add(student1);  // <---- Here the Issue ... but assigning it in the list of College 2 ... ws expecting Exception 

     // Saved College 1 & 2
     collegeDAO.save(college1);
     collegeDAO.save(college2);

      // Saved Successfully BUT

RESULT  大学表

 COLLEGE_XID     COLLEGE_NAME    
 --------------  --------------- 
 1               C_1             
 2               C_2 

学生表

 STUDENT_XID     STUDENT_NAME     COLLEGE_XID    
 --------------  ---------------  -------------- 
 1               S_1_C_2          1   

我期待一些例外,因为来自孩子和父母的作业在大学 - 学生的例子中不匹配  另一件困扰我的事情是hibernate生成的查询

Hibernate: insert into COLLEGE (COLLEGE_NAME) values (?)
Hibernate: insert into COLLEGE (COLLEGE_NAME) values (?)
Hibernate: insert into STUDENT (COLLEGE_XID, STUDENT_NAME) values (?, ?)

即先保留大学1,然后学院2秒,拯救学生作为大学2的孩子,但结果却显示为大学1的孩子

1 个答案:

答案 0 :(得分:0)

这是因为您添加了mappedBy属性并使学生成为关联的所有者。 由于学生实体是所有者,它将维持关系,而休眠将忽略学院方面的变化。