ssh中修改关联关系报nested exception is org.hibernate.HibernateException: identifier

来源:互联网 发布:知柏地黄丸吃多久 编辑:程序博客网 时间:2024/06/13 05:13

首先声明:此问题不是修改单个实体的identifier 导致,而是修改关联关系实体identifier 导致,如果您不属于后者请节约您的时间^^.倡导快速解决问题,从你我做起。

今天做ssh中many-to-one关联关系修改时,每次修改一个实体的关联实体时,总会遇到:

[JOFFICE] 2012-05-24 15:18:35 ERROR [http-apr-8080-exec-3] UkKnowTypeAction.save(289) | identifier of an instance of com.ulane.know.model.know.UkKnowTemplate was altered from 89 to 21; nested exception is org.hibernate.HibernateException: identifier of an instance of com.ulane.know.model.know.UkKnowTemplate was altered from 89 to 21

save() 如下:

public String save() {
try {
if (ukKnowType.getKnowTmpId() != null) {
UkKnowTemplate uktt = ukKnowTemplateService.get(ukKnowType.getKnowTmpId());
ukKnowType.setUkKnowTemplate(uktt);                      ///============>关注点

/*....code.*/
UkKnowType orgUkKnowType = ukKnowTypeService.get(ukKnowType.getKnowTypeId());
try {
BeanUtil.copyNotNullProperties(orgUkKnowType, ukKnowType);
ukKnowTypeService.save(orgUkKnowType);    ///============>关注点
} catch (Exception ex) {
logger.error(ex.getMessage());
}
}
setJsonString("{success:true}");
return SUCCESS;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}

发现每次修改ukKnowType关联的UkKnowTemplate以后,在service.save()时就报上面的异常。但是关联关系怎么可能不能修改呢?否则这样的功能怎么会有市场?

既然提示修改关联对象的id异常,那就先把关联实体置为null,再set新的关联实体这样总可以了吧。结果果然可以,太开心了。修改后的save():

public String save() {
try {

UkKnowTemplate uktt = null;     //***************修改点
if (ukKnowType.getKnowTmpId() != null) {
uktt = ukKnowTemplateService.get(ukKnowType.getKnowTmpId());  //***************修改点
ukKnowType.setUkKnowTemplate(null);                      //***************修改点

/*....code.*/
UkKnowType orgUkKnowType = ukKnowTypeService.get(ukKnowType.getKnowTypeId());
try {
BeanUtil.copyNotNullProperties(orgUkKnowType, ukKnowType);

orgUkKnowType.setUkKnowTemplate(uktt); //***************修改点

ukKnowTypeService.save(orgUkKnowType);   
} catch (Exception ex) {
logger.error(ex.getMessage());
}
}
setJsonString("{success:true}");
return SUCCESS;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}


总结:开始的思路是想在spring注入的ukKnowType(包含用户修改的各个属性)对象中把修改的关联对象填充进去,再通过hibenate获取数据库中的被修改的原数据orgUkKnowType,最后把ukKnowType的非空属性(提供给用户修改的)copy给orgUkKnowType,再保存实现修改功能。但是存在上面的问题,修改save后,搞定。