今天项目组有成员使用spring声明式事务出现下面异常,这里跟大家分享学习下。
异常信息:
org.springframework.orm.hibernate3.HibernateSystemException: identifier of an instance of com.xxx.entity.Activity was altered from 33 to null; nested exception is org.hibernate.HibernateException: identifier of an instance of com.xxx.entity.Activity was altered from 33 to null
出现异常代码:(都是在service层中的一个方法里)
@Service
@Transactional
public class GroupServiceImpl extends CoreManagerImpl<Group> implements GroupService
省略
@Override
public Group updateGroup(Group group,Group old) throws Exception {
Group doGroupUpdate = doGroupUpdate(group, old);
List<SubGroup> subs = doSubGroupsUpdate(group.getSubGroups(), doGroupUpdate.getId());
doGroupUpdate.setSubGroups(subs);
Activity activity = updateActivity(doGroupUpdate);
activity.setId(null);//发生异常的原因
updateSeller(doGroupUpdate);
doGroupUpdate.setActivity(activity);
return doGroupUpdate;
}
修复后代码:
@Override
public Group updateGroup(Group group,Group old) throws Exception {
Group doGroupUpdate = doGroupUpdate(group, old);
List<SubGroup> subs = doSubGroupsUpdate(group.getSubGroups(), doGroupUpdate.getId());
doGroupUpdate.setSubGroups(subs);
Activity activity = updateActivity(doGroupUpdate);
//activity.setId(null);
updateSeller(doGroupUpdate);
doGroupUpdate.setActivity(activity);
return doGroupUpdate;
}
原因分析:
使用spring声明试事务,在整个事务(里面有多个子事务)没有提交成功,就将id主键设置成了null(主键不可以为null),所以会抛出上述异常。spring声明式事务是在所有子操作都完成一起提交事务的。