【问题标题】:How to delete all records in Hibernate including Child Records (@OneToMany)?如何删除 Hibernate 中的所有记录,包括子记录(@OneToMany)?
【发布时间】:2020-03-29 01:24:51
【问题描述】:

主要实体

public class CustomerAgreement implements Serializable {
    @OneToMany(mappedBy = "customerAgreement", orphanRemoval = true, fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    private List<CustomerAgreementPeriod> agreementPeriods;

子实体:

public class CustomerAgreementPeriod  implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "CustomerAgreementPeriodSeq", sequenceName = "CUST_AGT_PERIOD_SEQ")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "CustomerAgreementPeriodSeq")
    @Column(name = "ID")
    private Long id;
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "CUSTID")
    private CustomerAgreement customerAgreement;

主要:

em.getTransaction().begin();
em.createQuery("delete from CustomerAgreement").executeUpdate();
em.getTransaction().commit();

例外:

java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MASTERDATA.FK_J6TS8CGX06F90LLEMER78LFGG) violated - child record found
  • 我在其中一个答案中发现级联在删除 JPQL 时不起作用。
  • 使用 .remove(entity) 似乎不是好方法?
  • 先使用本机查询删除子查询,然后再使用父查询? (我有 5 个孩子)
  • 有人建议不要在 orphanremoval=true 的情况下使用 cascade,我已更改为 Cascade.Persist,但随后也出现了同样的异常

谁能建议如何在单个查询中删除实体,包括来自具有上述给定结构的 4-5 个不同表中的子实体。

【问题讨论】:

    标签: hibernate jpa hql jpql hibernate-mapping


    【解决方案1】:

    没有找到合适的方法,所以使用下面的原生查询:

    public void deleteAllNative() {
            em.createNativeQuery("DELETE FROM CUST_AGT_ATT_TAB").executeUpdate();
            em.createNativeQuery("DELETE FROM CUST_AGT_CUSTOM_TAB").executeUpdate();
            em.createNativeQuery("DELETE FROM CUST_AGT_PERIODS_TAB").executeUpdate();
            em.createNativeQuery("DELETE FROM CUST_AGT_ROLES_TAB").executeUpdate();
            em.createNativeQuery("DELETE FROM CUST_AGREEMENT_TAB").executeUpdate();
            em.flush();
        }
    

    我很伤心:(

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2019-06-27
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多