1.问题描述:
将业务代码放在service层,执行saveOrUpdate()时,出现对象已经存在的异常。
Exception in thread"main"org.hibernate.NonUniqueObjectException: 
a different object with the same identifier value was already exit。
2.怀疑数据库有两条id重复的数据?
实时证明,数据库只有一条
原因:
hibernate中,在service服务调用saveOrUpdate时,
因为session中有相同对象,抛出有重复对象的异常,实际上数据库也只有唯一一条数据,按道理应该执行update的。
源码:
/**
* Attempts to check whether the given key represents an entity already loaded within the
* current session.
* @param object The entity reference against which to perform the uniqueness check.
* @throws HibernateException
*/
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
Object entity = getEntity(key);   //在hibernate session中获取对象
if ( entity == object ) {
throw new AssertionFailure( "object already associated, but no entry was found" );
}
if ( entity != null ) {//如果对象存在就抛出异常....session就不能存在相同对象?????
throw new NonUniqueObjectException( key.getIdentifier(), key.getEntityName() );
}
}
解决方案:
Object obj = super.hibernateTemplate().merge(object)
super.hibernateTemplate().saveOrUpdate(obj)
将对象与session中的对象合并,返回合并后的对象进行update
public void updateAll(Collection<T> entities) {
for(T e : entities){
T merge = super.getHibernateTemplate().merge(e);
super.getHibernateTemplate().saveOrUpdate(merge);
}
}