【发布时间】:2014-08-27 10:30:06
【问题描述】:
当我尝试使用休眠模式保存或更新时,我收到了 ConstraintViolationException。当我为用户插入一个全新的对象时,保存效果很好,但是当我尝试更新时它失败了。
在数据库表中,我有一个唯一的非空主键和一个名为 userid 的唯一非空外键
我的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: 密钥“userid_UNIQUE”的重复条目“16”
数据库是这样的
我做错了什么,数据库条目不应该更新吗?
【问题讨论】:
-
所以你的方法“addCardForUser”实际上也更新了卡片?您是否尝试记录主键以检查您是否确实在更新主键?