newObj = getHibernateTemplate().merge(obj);
obj是一个游离对象,该方法将把obj中的属性更新到与obj主键一致的持久对象中,并返回该持久对象newObj。如果没有对应的持久对象,将会新建一个持久对象并将属性拷贝进去,并返回新对象。
参考:
Copy the state of the given object onto the persistent object with the same identifier. Follows JSR-220 semantics.
Similar to saveOrUpdate
, but never associates the given
object with the current Hibernate Session. In case of a new entity, the
state will be copied over as well.
Note that merge
will not
update the identifiers in the passed-in object graph (in contrast to TopLink)! Consider registering Spring's IdTransferringMergeEventListener
if you would like to have newly assigned ids transferred to the original object graph too.
如果上述方法新建了一个持久对象,持久对象的id并不会拷贝到obj中。如果想要拷贝到obj中,要注册IdTransferringMergeEventListener 监听器。
例如:
<property name="eventListeners"> <map> <entry key="merge"> <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" /> </entry> </map> </property>