# Hibernate update 和 saveOrUpdate区别

**URL:** <https://www.isharkfly.com/t/hibernate-update-saveorupdate/6487>\
**Category:** 程序语言\
**Created:** [May 24, 2011, 4:48pm UTC](https://www.isharkfly.com/t/hibernate-update-saveorupdate/6487 "2011-05-24T16:48:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [May 24, 2011, 4:48pm UTC](https://www.isharkfly.com/t/hibernate-update-saveorupdate/6487/1 "2011-05-24T16:48:47Z")

</div>

这个是比较好理解的，顾名思义，saveOrUpdate基本上就是合成了save和update,而update只是update;引用hibernate reference中的一段话来解释他们的使用场合和区别  
通常下面的场景会使用update()或saveOrUpdate()：

程序在第一个session中加载对象,接着把session关闭

该对象被传递到表现层

对象发生了一些改动

该对象被返回到业务逻辑层最终到持久层

程序创建第二session调用第二个session的update()方法持久这些改动

saveOrUpdate(po)做下面的事:  
如果该po对象已经在本session中持久化了，在本session中执行saveOrUpdate不做任何事。如果savaOrUpdate(新po)与另一个与本session关联的po对象拥有相同的持久化标识(identifier)，抛出一个异常`
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [org.itfuture.[url]www.po.Xtyhb[/url]#5]`saveOrUpdate如果对象没有持久化标识(identifier)属性，对其调用save() ，否则update() 这个对象。
