繁体   English   中英

如何通过Hibernate删除关联实体

[英]How to delete an associate entities through Hibernate

我有两个类,对应于两个表。 请假定所有的获取器和设置器都已添加到类中。

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实体时,它会成功删除它,包括关联的Address实体。

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();
}

但是,当我在引入另一个类,组织以及相应的表之后,取消对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字段的形式在Organization实体中被引用。 我试图找出解决方案,但没有得到任何详细说明。

那么有人可以帮助我解决此Exception错误以及具体的理由吗?

我的想法是尝试将orphanRemoval = true (在OneToMany -Line中)添加到Organization ,然后仅从集合中删除Employee。 它应该很好地删除所有内容。

有点过时了: https : //docs.oracle.com/cd/E19798-01/821-1841/giqxy/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM