【问题标题】:delete values in child table when you delete values in parrent table JPA删除父表 JPA 中的值时删除子表中的值
【发布时间】:2016-08-28 17:55:32
【问题描述】:

父表:货币 - 有 2 个字段表示子表中的外键:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "inputCurrency")
List<Rate> ratesIC;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "outputCurrency")
List<Rate> ratesOC;

子表:Rate - has2 个字段引用父表中的主键:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "INPUT_CURRENCY")
private Currency inputCurrency;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "OUTPUT_CURRENCY")
private Currency outputCurrency;

问题:如何删除一种货币以及包含该货币的所有汇率?我不想用 orphanRemoval = true Currency 中的 ratesIC 和 ratesOC 字段。

我尝试过的: 我首先尝试删除包含该货币的所有汇率:

@NamedQuery(
       name = "deleteRateByCurrencyName",
       query = "DELETE FROM Rate r "
       + "WHERE r.inputCurrency.currency = :cName "
       + "OR r.outputCurrency.currency = :cName")

然后从父表中删除名称为货币的货币:

@NamedQuery(
       name = "deleteCurrencyByCurrencyName",
       query = "DELETE FROM Currency c "
       + "WHERE c.currency =:cName")

我是通过调用这个函数做到的:

public void removeCurrencyByNameAndAllRatesContainingThatCurrency(String currency) throws CurrencyNotFoundException {
        try {
            em.createNamedQuery("deleteRateByCurrencyName")
                    .setParameter("cName", currency)
                    .executeUpdate();
            em.createNamedQuery("deleteCurrencyByCurrencyName")
                    .setParameter("cName", currency)
                    .executeUpdate();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new CurrencyNotFoundException("The currency " + currency + " doesn't exist!");
        }
    }

我得到了什么:

Internal Exception: java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'CURRENCY' caused a violation of foreign key constraint 'RATEOUTPUTCURRENCY' for key (3).  The statement has been rolled back.
Error Code: 20000

【问题讨论】:

    标签: jpa jpql java-ee-7


    【解决方案1】:

    我不知道您使用的是哪个 JPA 提供程序,因为您提供的我尝试过的查询给了我一个不同的错误。在带有 Hibernate 5.0.7.Final 的 Wildfly 10 下,我得到了以下工作:

    em.createQuery("delete from Rate r where r in (select r from Rate r where r.inputCurrency.currency = :currency or r.outputCurrency.currency = :currency)")
        .setParameter("currency", "USD")
        .executeUpdate();
    em.createQuery("delete from Currency where currency=:sCurrency")
        .setParameter("sCurrency", "USD")
        .executeUpdate();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 2020-11-26
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多