Hibernate Cascading Delete未按预期工作

时间:2011-04-15 21:03:25

标签: java hibernate cascading-deletes

我正在使用hibernate 3并尝试删除数据库中的记录,并且删除操作无法正常工作。模式hibernate正在反对(在伪代码中):

create table Employer(
    employer_id number(12) primary key,
    employer_name varchar2(50)
);

create table Employee(
    employee_id number(12) primary key,
    employee_name varchar2(50),
    employer_id number(12) foreign key references employer.employer_id not null
);

create table Employee_Roles(
    role_id number(12) primary key,
    employee_id number(12) foreign key references employee.employee_id not null,
    role varchar2(50)
);

我的hibernate类映射看起来像:

@Entity
public class Employer{

    @Id
    @Column(name = "EMPLOYER_ID")
    private long id;

    @Column
    private String name;


    @OneToMany(targetEntity = Employee.class, fetch = FetchType.EAGER)
    @JoinColumn(name = "employer_id")
    @Cascade(CascadeType.ALL)
    private Set<Employee> employees;
}

@Entity
public class Employee{

    @ManyToOne(targetEntity = Employer.class)
    @JoinColumn(name = "employer_id")
    @Cascade(value = CascadeType.SAVE_UPDATE)
    private Employer employer;

    @OneToMany(targetEntity = EmployeeRole.class, fetch = FetchType.EAGER)
    @JoinColumn(name = "employee_id")
    @Cascade(CascadeType.ALL)
    private Set<Employee> employees;
}

@Entity
public class EmployeeRole{

    @ManyToOne(targetEntity = Employee.class)
    @JoinColumn(name = "employee_id")
    @Cascade(value = CascadeType.SAVE_UPDATE)
    private Employee employee;
}

现在有了这个配置我打电话:

getCurrentSession().delete(someEmployerEntity);

正在发生的事情是:

Hibernate: update EMPLOYEE set EMPLOYEE_ID=null where EMPLOYEE_ID=?
Hibernate: update EMPLOYEE_ROLE set employee_id=null where employee_id==?
[2011-04-15 15:59:53,487] JDBCExceptionReporter WARN  - SQL Error: -10, SQLState: 23502
[2011-04-15 15:59:53,487] JDBCExceptionReporter ERROR - integrity constraint violation: NOT NULL check constraint; SYS_CT_10058 table: EMPLOYEE_ROLE

并引发异常。我期待的结果是session.remove(..)调用是要删除的雇主记录,以及与雇主关联的所有员工记录以及与删除的员工记录关联的所有EmployeeRole记录。这是正确的假设吗?或者我在这里误解了一个关键概念?

1 个答案:

答案 0 :(得分:4)

级联all-delete-orphan应解决您的问题。但是,它是Hibernate的一部分,而不是EJB标准。如果您想这样做并且不会陷入供应商的解决方案中,我建议您查看this article

祝你好运!

编辑:按照你的建议我将'mappedBy'属性添加到@OneToMany注释中,这似乎是使用inverse =“true”来指定拥有关系的注释方式。关系的相关变化部分如下所示:

public class Employee{

    @OneToMany(targetEntity = EmployeeRole.class, mappedBy="employee", fetch = FetchType.EAGER,  cascadeType=CascadeType.ALL)
    private Set<EmployeeRole> employeeRoles;
}


public class Employer{

    @OneToMany(targetEntity = Employee.class, mappedBy="employer", fetch = FetchType.EAGER, cascadeType=CascadeType.ALL)
    private Set<Employee> employees;
}