【问题标题】:How to update primary key of parent table that will automatically update child table foreign key in hibernate?如何更新将在休眠中自动更新子表外键的父表的主键?
【发布时间】:2018-02-02 14:48:04
【问题描述】:

在我的项目中,我有两个表:

1)银行用户 2)银行账户

BankUser 与 BankAccount 具有 @OneToMany 关系。我将 cascade = cascadeType.ALL 提供给 BankUser,例如:

@OneToMany(mappedBy="bankUser" , cascade = CascadeType.ALL)          
    public Collection<BankAccount> getBankAccount() {
        return bankAccount;
    }

所以我想更新表 BankUser 的主键,休眠将自动更新 BankAccount 表的外键。表 BankUser 的主键是 BankAccount 表的外键。所以,我想同时更新 pk 和 fk。

我尝试了两种方式:

1) SQL查询:

 SQLQuery sql = sf.getCurrentSession().createSQLQuery("update Bank_User b set b.user_id = 456 where b.user_id = 3");
 int id = sql.executeUpdate();

2) 检索对象 n 更新:

BankUser b = (BankUser) sf.getCurrentSession().createQuery("select b from 
BankUser b where b.id = 3").uniqueResult();
b.setId(456);
b.setUserName("cascade_new");
sf.getCurrentSession().saveOrUpdate(b);  

它给出的异常如下:

 (SqlExceptionHelper.java:logExceptions:144) Cannot delete or update a parent row: a foreign key constraint fails (`myproject`.`bank_account`, CONSTRAINT `FK39272A436B2B33` FOREIGN KEY (`BankUser_Id`) REFERENCES `bank_user` (`User_Id`))
Unknown Exception Occured: org.hibernate.exception.ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`myproject`.`bank_account`, CONSTRAINT `FK39272A436B2B33` FOREIGN KEY (`BankUser_Id`) REFERENCES `bank_user` (`User_Id`))

【问题讨论】:

    标签: java mysql spring hibernate jpa


    【解决方案1】:

    您永远不应该更新实体的主键。更多详情,请查看此answer

    【讨论】:

    • 好的,但是我们可以在 MySQL 中使用 ON DELETE CASCADE ON UPDATE CASCADE 更新它。
    • 在关系数据库的情况下你是对的。但是hibernate不应该被视为一个数据库,它是一个OR映射器,基于一个面向对象的实体模型。例如,更改实体的 pk 将使 entityManager/session 缓存无效。如果您以编程方式更改实体的身份,则会话结束时自动更新等功能将不再起作用。
    【解决方案2】:

    是的,我明白了。谢谢兄弟。我们无法在休眠中更新主键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      相关资源
      最近更新 更多