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监听器。
例如:
参考
Extension of Hibernate's DefaultMergeEventListener, transferring the ids of newly saved objects to the corresponding original objects (that are part of the detached object graph passed into the merge
method).
Transferring newly assigned ids to the original graph allows for continuing to use the original object graph, despite merged copies being registered with the current Hibernate Session. This is particularly useful for web applications that might want to store an object graph and then render it in a web view, with links that include the id of certain (potentially newly saved) objects.
The merge behavior given by this MergeEventListener is nearly identical to TopLink's merge behavior. See PetClinic for an example, which relies on ids being available for newly saved objects: the HibernateClinic
and TopLinkClinic
DAO implementations both use straight merge calls, with the Hibernate SessionFactory configuration specifying an IdTransferringMergeEventListener
.
Typically specified as entry for LocalSessionFactoryBean's "eventListeners" map, with key "merge".