如何在删除父项时更新子项

时间:2013-03-05 07:00:37

标签: hibernate hibernate-mapping hibernate-annotations

我的要求是当我删除父项时,不应删除子项,而不是删除子项,其中一个外键的子列department_ID必须更新一些值,比如一个部门(父表) )包含许多员工和员工(子表)表有Department_ID作为外键列。问题是当我删除父表时我没有反映在孩子身上因为我有updatable=false如果我将它设为true然后在删除parent时,child列设置为null或者如果我更新父级,那么也将子Department_Id列设置为null,这违反了要求,这就是为什么我将其设为false。我不想要当父进行任何更改时,要更新的子只有更改应反映在删除操作上,仅在一列上。请帮帮我,我该怎么办?感谢

这是我的父表部门代码

  @Id
  @Column(name = "DEPARTMENT_ID")
  private String departmentId;

  @OneToMany(fetch = FetchType.EAGER)
  @JoinColumn(name = "DEPARTMENT_ID",insertable=false,updatable=false)
  Collection<Employee> employeeList;

这是我的孩子表员工

    @Id
    @Column(name = "EMPLOYEE_NUMBER")
    private int employeeNumber;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;

    @Column(name = "DEPARTMENT_ID")
    private String departmentId;

1 个答案:

答案 0 :(得分:0)

让儿童方保持一对多的关系,因此您需要将 mappedBy 属性添加到@OneToMany。

@Id
@Column(name = "DEPARTMENT_ID")
private String departmentId;

@OneToMany(fetch = FetchType.EAGER, mappedBy="departmentId")
@JoinColumn(name = "DEPARTMENT_ID",insertable=false,updatable=false)
Collection<Employee> employeeList;

维持以下关系:

employee.departmentId = newDepartmentId; //or set it null to detach from the old dept