簡體   English   中英

如何更新父表的主鍵,它將在冬眠時自動更新子表的外鍵?

[英]How to update primary key of parent table that will automatically update child table foreign key in hibernate?

在我的項目中,我有兩個表:

1)BankUser 2)BankAccount

BankUser與BankAccount具有@OneToMany關系。 我給cascadeUser提供cascade = CascadeType.ALL,如下所示:

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

所以我要更新表BankUser的主鍵,休眠將自動更新BankAccount表的外鍵。表BankUser的主鍵是BankAccount表的外鍵。 因此,我想同時更新pk和fk。

我嘗試了兩種方式:

1)SQLQuery:

 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`))

您永遠不要更新實體的主鍵。 有關更多詳細信息,請查看此答案

是的,我明白了。謝謝兄弟。 我們無法在休眠狀態下更新主鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM