在我的项目中,我有两张桌子:
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`))