我尝试按如下方式实现cascaded =“delete”,但只删除了员工行而不是相应的工资行。 Employee pojo类是:
public class Employee {
int empid;
String ename;
Salary sal;
//gettrs and setters
工资pojo类是:
public class Salary {
int sid;
double netsal;
Employee employee;
//getters and setters
employee.hbm文件是:
<hibernate-mapping>
<class name="employee.Employee" table="EMPLOYEE">
<id name="empid" type="int">
<column name="EMPID" />
<generator class="assigned" />
</id>
<property name="ename" type="java.lang.String">
<column name="ENAME" />
</property>
<many-to-one name="sal" class="employee.Salary" cascade="delete">
<column name="sid" />
</many-to-one>
</class>
salary.hbm文件是:
<hibernate-mapping>
<class name="employee.Salary" table="SALARY">
<id name="sid" type="int">
<column name="sid" />
<generator class="increment" />
</id>
<property name="netsal" type="double">
<column name="netsal" />
</property>
</class>
并将相应的mysql表创建为:
create table employee(EMPID int(5) primary key,ENAME varchar(20),sid int(5),foreign key(sid) references salary(sid));
create table salary(sid int(5) primary key,netsal int(5));
插入以下记录后:
SessionFactory sf= new Configuration().configure().buildSessionFactory();
session= sf.openSession();
Transaction tx= session.beginTransaction();
Employee emp=new Employee();
emp.setEmpid(12);
emp.setEname("some name");
Salary sal=new Salary();
sal.setNetsal(12000);
emp.setSal(sal);
sal.setEmployee(emp);
tx.commit();
session.flush();
session.close();
当我做的时候
Query query = session.createQuery("delete from employee e where e.empid=12");
query.executeUpdate();
然后删除employee表中的条目,但工资表中的相应条目仍然存在。那么我如何确保相应的工资条目也被删除? 感谢。
答案 0 :(得分:10)
使用DML样式的删除查询删除实体时,级联不起作用。仅当您使用会话删除员工时,它才会起作用:
Employee e = (Employee) session.load(Employee.class, 12);
session.delete(e);