Caused by: org.hibernate.HibernateException: identifier of an instance of ... is alterde from
Hibernate的提示错误
org.hibernate.HibernateException: identifier of an instance of .[类名]. is alterde from [数字] to [数字]
identifier of an instance of org.xx.xx was altered from 311097668476600320 to 311097668610818048; nested exception is org.hibernate.HibernateException: identifier of an instance of org.xx.xxx was altered from 311097668476600320 to 311097668610818048
原因:
先看错误代码:
/**
* 新增用户权限
* @param users
* @param userRole
* @return 执行结果
* @throws Exception
*/
public String insert(JSONArray userIds, JSONArray userRole) throws Exception {
//将 JSONArray 转换实体类
List<Role> userRoleList = (List<Role>) BaseUtils.toClassList(userRole, Role.class);
String result = "";
//循环要批量添加的用户权限
for (int i = 0; i < userIds.size(); i++) {
JSONObject jsonObject = userIds.getJSONObject(i);
//循环转换后的用户 List
for (Role role: userRoleList) {
//将userId赋值给权限
role.setRole_list(jsonObject.getString("userId"));
role.setId(IdWorker.getInstance().nextId());
//........判空之类的处理
result = BaseUtils.insert(role);
}
}
return result;
}
错误提示:
原因是由于在一个事务中更新了主键,而主键是不能被更新的.
解决方案:
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.BeanUtils;
/**
* PS:使用 Spring的BeanUtils可能会出现小问题,建议使用apache的BeanUtils
* 新增用户权限
* @param users
* @param userRole
* @return 执行结果
* @throws Exception
*/
public String insert(JSONArray userIds, JSONArray userRole) throws Exception {
//将 JSONArray 转换实体类
List<Role> userRoleList = (List<Role>) BaseUtils.toClassList(userRole, Role.class);
String result = "";
//循环要批量添加的用户权限
for (int i = 0; i < userIds.size(); i++) {
JSONObject jsonObject = userIds.getJSONObject(i);
//循环转换后的用户 List
for (Role role: userRoleList) {
/***************新增解决方法******************/
Role newRole = new Role();
//copy到新对象后进行 操作
BeanUtils.copyProperties(role, newRole);
/**********************************************/
//将userId赋值给权限
role.setRole_list(jsonObject.getString("userId"));
role.setId(IdWorker.getInstance().nextId());
//........判空之类的处理
result = BaseUtils.insert(role);
}
}
return result;
}
BeanUtils.copyProperties 详解,请点击学习
血的教训!
至此,完美解决
END