使用hibernate注释删除父子关系上的问题



要求是当父级被删除时,所有相关的子级必须被删除。当使用hibernate注释删除父级时,我面临删除子级的问题,我的父级表是Employee,子表是EmployeeProject,子表在数据库中有Employee_Number的外键约束,问题是当我删除父级时,下面的错误即将出现,请告诉我映射中的问题在哪里,谢谢

  Hibernate: select employee_.EMPLOYEE_NUMBER, employee_.ADDRESS_1 as ADDRESS2_0_, employee_.ADDRESS_2 as ADDRESS3_0_, employee_.CITY as CITY0_, employee_.DATE_OF_ANNIVERSARY as DATE5_0_, employee_.DATE_OF_BIRTH as DATE6_0_, employee_.DATE_OF_JOINING as DATE7_0_, employee_.DATE_OF_LEAVING as DATE8_0_, employee_.DEPARTMENT_ID as DEPARTMENT9_0_, employee_.FIRST_NAME as FIRST10_0_, employee_.LAST_NAME as LAST11_0_, employee_.MOBILE_NUMBER as MOBILE12_0_, employee_.pincode as pincode0_, employee_.REASON_FOR_LEAVING as REASON14_0_, employee_.state as state0_, employee_.TELEPHONE_NUMBER as TELEPHONE16_0_, employee_.TITLE as TITLE0_ from Employees employee_ where employee_.EMPLOYEE_NUMBER=?
Hibernate: delete from Employees where EMPLOYEE_NUMBER=?
4 Mar, 2013 12:33:32 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1451, SQLState: 23000
4 Mar, 2013 12:33:32 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot delete or update a parent row: a foreign key constraint fails (`employee/employee_project`, CONSTRAINT `FKC1804A88229473A9` FOREIGN KEY (`EMPLOYEE_NUMBER`) REFERENCES `employees` (`EMPLOYEE_NUMBER`))

这是父映射

    @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
    Collection<EmployeeProject> employeeProjects = new ArrayList<EmployeeProject>();

这是子表映射

    @ManyToOne
    @JoinColumn(name = "EMPLOYEE_NUMBER", insertable = false, updatable = false)
    Employee employee;

这是其父(雇员)被删除的方法

@Override
public boolean deleteEmployee(Employee employee) {
    Transaction transaction = null;
    boolean flag;
    try {
        transaction = session.beginTransaction();
        session.delete(employee);
        transaction.commit();
        flag = true;
    } catch (HibernateException exception) {
        if (transaction != null)
            transaction.rollback();
        flag = false;
    }
    return flag;
}

确保在数据库模式中也有标记为CASCADE的外键关系,假设这是您想要的。Hibernate的级联将负责删除Hibernate对象,但它本身不会使DELETE杀死尚未转化为应用程序中的对象的子记录。

try this,

          t = session.beginTransaction();
      ExperimentImpl persistentExperiment = session.load(Employee.class, 
             employee.getId());
    session.delete(persistentExperiment);
    t.commit();

将尝试使用您想要删除的实验的主键,并在实际删除它之前加载:

相关内容

  • 没有找到相关文章

最新更新