如何在一对多关系中使关联为null?

时间:2014-09-26 13:04:04

标签: java hibernate

我试图让学生协会之一与大学无关,但在同花顺/提交上没有发生任何事情。我不确定是什么问题。这是我的大学和学生实体

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();

2 个答案:

答案 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()强制刷新。

答案 1 :(得分:0)

由于Student拥有关系,因此您应将student.college设为null并更新

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