PurposeMerges a domain class instance back into the current persistence context and returns a new merged instance.
def b = new Book(title: "The Shining") b = b.merge()
mergemethod is similar in function to the save method, but not in behaviour.
mergeallows the merging of "detached" instances such as those stored in the HTTP session. Each persistent instance is associated with a persistence context. A new persistence context is created for each request. The result is that objects stored in the HTTP session lose their persistence context on subsequent requests. In this case you can't simply call save as the domain class is not associated with a current context.The
mergemethod on the other hand lets you merge a detached object's state back into the current Hibernate session. Unlike the
savemethod this method returns a new instance of the class representing the re-attached object. In other words you must write code like this:
If you don't use the return value of the
book = book.merge()
mergemethod then you still have access to the original unmodified detached instance and you will get errors such as lazy initialization exceptions.The
mergemethod is defined in the Hibernate documentation as follows:
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. If the given instance is unsaved, save a copy of and return it as a newly persistent instance.The
mergemethod is equivalent to the Hibernate merge method.Parameters:
validate(optional) - Set to
falseif validation should be skipped
flush(optional) - When set to
trueflushes the persistence context, hence persisting the object immediately