我有两个班级,并且对应两个班级。请假设所有的getter和setter都已添加到类中。
public class Employee implements Serializable {
//@ManyToOne( cascade = CascadeType.PERSIST, targetEntity = RackEntity.class )
//@Fetch( FetchMode.SELECT )
//@JoinColumn( name = "orgName", referencedColumnName = "orgName", nullable = true )
//private Organization org;
private Long id;
private string empName;
@LazyCollection( LazyCollectionOption.FALSE )
@OneToMany( mappedBy = "emp", cascade = { CascadeType.ALL } )
@Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE,
org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST } )
private Set<Address> empAddress;
}
和
public class Address implements Serializable {
@ManyToOne( cascade = CascadeType.PERSIST, targetEntity = RackEntity.class )
@Fetch( FetchMode.SELECT )
@JoinColumn( name = "empName", referencedColumnName = "empName", nullable = true )
private Employee emp;
private Long id;
private String street;
private String block;
}
现在,当我尝试删除Employee实体时,它成功删除了它,包括相关的地址实体。
public void deleteById(Long id) {
logger.info("Deleting Employee {}", id);
Employee entity = (Employee) sessionFactory.getCurrentSession()
.get(Employee.class, id);
sessionFactory.getCurrentSession().delete(entity);
sessionFactory.getCurrentSession().flush();
}
但是当我在引入另一个类,Organization以及相应的表之后取消注释Employee类中的代码时会出现问题,如下所示:
public class Organization implements Serializable {
private Long id;
private string orgName;
@LazyCollection( LazyCollectionOption.FALSE )
@OneToMany( mappedBy = "org", cascade = { CascadeType.ALL } )
@Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE,
org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST } )
private Set<Employee> emps;
}
这里,在适当填充数据库之后,当我尝试使用相同的方法删除Employee实体时,我得到以下异常:
org.hibernate.ObjectDeletedException:已删除的对象将通过级联重新保存(从关联中删除已删除的对象)
我想这是因为Employee实体仍然以字段emps的形式在组织实体中被引用。我试图找出解决方案,但没有得到任何精心设计的解决方案。
所以任何人都可以帮我解决这个异常错误以及具体的理由吗?
答案 0 :(得分:0)
我的想法是尝试将orphanRemoval = true
(在OneToMany
- 行中)添加到Organization
,然后只删除群组中的员工。它应该很好地删除所有东西。