Hibernate在多对一的双向映射中删除子行

时间:2014-05-21 07:07:20

标签: java hibernate cascade

您好我已经创建了employeeseentity和employeedepartment实体,这里我已经建立了这两个实体之间的双向映射。现在问题是在更新时我需要从表中删除所有子项,我需要将新数据保存到该列表中,但是这里列表没有从表中删除我的实体映射是这样的。

在EmployeeDepartmentEntity

 @ManyToOne
        @JoinColumn(name = "employeeid")
        private EmployeeEntity employeeentity;


**In EmployeeEntity**


@OneToMany(mappedBy = "employeeentity")
    @OrderBy("id")
    @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.remove})
    private List<EmployeeDeparment> empdep = new ArrayList<EmployeeDeparment>();

我这样做

Session session = HibernateUtil.getSessionFactory().openSession();
        EmployeeEntity editemployee = (EmployeeEntity) session.get(EmployeeEntity.class, 95);
        List<EmployeeDeparment> list = editemployee.getEmpdep();

        Iterator<EmployeeDeparment> ite = list.iterator();

        while (ite.hasNext()) {
            EmployeeDeparment value = ite.next();
            ite.remove();
        }
        session.saveOrUpdate(editemployee);
        session.beginTransaction().commit();

更新:

如果我在employeeEntity中仅使用saveorupdate而如果我正在删除

for(EmployeeDeparment deparment:list){
        session.delete(deparment);
        }

我得到例外。

Exception in thread "main" org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations):

2 个答案:

答案 0 :(得分:0)

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    EmployeeEntity editemployee = (EmployeeEntity) session.get(EmployeeEntity.class, 95);
    List<EmployeeDeparment> list = editemployee.getEmpdep();

    Iterator<EmployeeDeparment> ite = list.iterator();

    while (ite.hasNext()) {
        EmployeeDeparment value = ite.next();
        session.delete(value)
    }
    session.saveOrUpdate(editemployee);
    tx.commit();
    session.close();

使用此选项并删除@cascade

@OneToMany(mappedBy = "employeeentity")
    @OrderBy("id")
    private List<EmployeeDeparment> empdep = new ArrayList<EmployeeDeparment>();

答案 1 :(得分:-1)

从迭代器中删除与从列表中删除迭代器派生的不同。迭代的对象是分离的。