如何更新将在hibernate中自动更新子表外键的父表的主键?

时间:2018-02-02 14:48:04

标签: java mysql spring hibernate jpa

在我的项目中,我有两张桌子:

1)BankUser 2)BankAccount

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

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

所以我想要更新表BankUser的主键,hibernate会自动更新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)Retrive Object n update:

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

2 个答案:

答案 0 :(得分:0)

您永远不应该更新实体的主键。有关详细信息,请查看此answer

答案 1 :(得分:0)

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