當我嘗試使用hibernate saveOrUpdate時,出現ConstraintViolationException。當我爲用戶插入一個全新的對象時,保存完美,但是當我嘗試更新它時失敗。爲外鍵引發ConstraintViolationException
在數據庫表我有一個獨特的NOT NULL主鍵和唯一不爲空命名用戶標識外鍵
我的POJO聲明如下;
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name="userid")
private int userid;
@Column(name = "homephonenumber")
protected String homeContactNumber;
@Column(name = "mobilephonenumber")
protected String mobileContactNumber;
@Column(name = "photo")
private byte[] optionalImage;
@Column(name = "address")
private String address;
我的插入語句如下所示;
public boolean addCardForUser(String userid, Card card) {
if(StringUtilities.stringEmptyOrNull(userid)){
throw new IllegalArgumentException("Cannot add card for null or empty user id");
}
if(card == null){
throw new IllegalArgumentException("Cannot null card to the database for user " + userid);
}
SessionFactory sf = null;
Session session = null;
try{
sf = HibernateUtil.getSessionFactory();
session = sf.openSession();
session.beginTransaction();
session.saveOrUpdate(card);
session.getTransaction().commit();
return true;
}catch(Exception e){
logger.error("Unable to add Card to the database for user " + userid);
}finally{
DatabaseUtilities.closeSessionFactory(sf);
DatabaseUtilities.closeSession(session);
}
return false;
}
我得到的異常說
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 重複條目 '16' 關鍵 'userid_UNIQUE'
和數據庫看起來像這樣
我做錯了什麼,數據庫條目是否應該更新?
所以你的方法「addCardForUser」實際上更新卡?你是否嘗試記錄主鍵來檢查你是否正在更新? – Pablo 2014-08-27 10:51:07