【发布时间】: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