作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在使用 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 记录。这是一个正确的假设吗?还是我误解了这里的一个关键概念?
最佳答案
Cascade 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;
}
关于java - Hibernate 级联删除未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682355/
我是一名优秀的程序员,十分优秀!