2014-09-26 69 views
0

我正在努力使大學之一的學生協會爲空,但沒有任何事情發生在刷新/提交上。我不確定是什麼問題。這裏是我的大學和學生實體如何使關聯在一對多關係中爲空?

public class College { 

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private int collegeId; 
    private String collegeName; 
    @OneToMany(mappedBy="college", cascade=CascadeType.ALL) 
    private List<Student> students; 

    public String getCollegeName() { 
     return collegeName; 
    } 
    public void setCollegeName(String collegeName) { 
     this.collegeName = collegeName; 
    } 
    public List<Student> getStudents() { 
     return students; 
    } 
    public void setStudents(List<Student> students) { 
     this.students = students; 
    } 
    public int getCollegeId() { 
     return collegeId; 
    } 
    public void setCollegeId(int collegeId) { 
     this.collegeId = collegeId; 
    } 


} 


@Entity 
public class Student { 

    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private int studentId; 
    private String studentName; 
    private boolean bachelor; 
    @ManyToOne 
    private College college; 

    public String getStudentName() { 
     return studentName; 
    } 
    public void setStudentName(String studentName) { 
     this.studentName = studentName; 
    } 
    public boolean isBachelor() { 
     return bachelor; 
    } 
    public void setBachelor(boolean bachelor) { 
     this.bachelor = bachelor; 
    } 
    public College getCollege() { 
     return college; 
    } 
    public void setCollege(College college) { 
     this.college = college; 
    } 
    public int getStudentId() { 
     return studentId; 
    } 
    public void setStudentId(int studentId) { 
     this.studentId = studentId; 
    } 

} 

這裏是我試圖使大學之一的學生協會空,但沒有什麼事情發生在刷新/提交。我不確定在這裏錯過了什麼?

Session session1 = factory.openSession(); 
    Transaction tx1 = session1.beginTransaction(); 
    College College1 = (College)session1.get(College.class, 1); 
    List <Student> students = College1.getStudents(); 
    System.out.println("student size is " + students.size()); 
    students.remove(0); 
    System.out.println("student size is " + College1.getStudents().size()); 
    session1.update(College1); 

    session1.flush(); 
    tx1.commit(); 
    session1.close(); 

回答

0

由於Student被擁有的關係,你應該設置student.college爲空,更新

List <Student> students = College1.getStudents(); 
students.get(0).setCollege(null); 
students.remove(0); 
session1.update(students.get(0)); 
0

orhpanRemoval標誌添加到收藏:

@OneToMany(mappedBy="college", cascade=CascadeType.ALL, orphanRemoval = true) 
private List<Student> students; 

第二件事 - 你不必撥打:

session1.update(College1); 
session1.flush(); 

College1已經被EntityManager管理的,因此將同步DB,flush()在這裏是不需要的,因爲在默認情況下,commit()強制刷新。