Hibernate通过update来处理游离状态对象
摘自圣思园hibernate18. 领域对象的三种状态深入详解- 25分钟
上一篇文章中讲到hibernate中对象的三种状态。
http://alleni123.iteye.com/admin/blogs/1977132
这里要说的就是通过update语句对游离状态进行持久化。在开发中是比较常用的一个方法。
先看一下hibernate文档对update方法的说明:
void update(Object object)
Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown. This operation cascades to associated instances if the association is mapped with cascade="save-update".
要理解的是中间那句"If there is a persistent instance with the same identifier, an exception is thrown"
这个意思其实是说, 如果我们执行
/*** Attemps to check whether the given key represents an entity already loaded with the current session.* @param object The entity reference against which to perform the uniqueness check**/public void checkUniqueness(EntityKey key, Object object) { //这里的参数是1和我们自定义的User对象。 Object entity=getEntity(key), //Object entity=getEntity(key)执行之后entity被赋予了get获取的那个User对象,该对象被从session缓存中提取出来。 if(entity==object) { throw new AssertionFailure ("object already associated, but no entry was found");} if(entity!=null){//由于entity!=null成立, 于是抛出NonUniqueObjectException。 throw new NonUniqueObjectException(key.getIdentifier(), key.getEntityName()); }}