Skip to content

Commit fc0d11b

Browse files
committed
HHH-19878 explain how to use find() to control merge()
1 parent 8a56476 commit fc0d11b

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

documentation/src/main/asciidoc/introduction/Interacting.adoc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,28 @@ Book book =
640640

641641
Notice that this code fragment is completely typesafe, again thanks to <<metamodel-generator,Hibernate Processor>>.
642642

643+
[[controlling-merge]]
644+
=== Controlling state retrieval during merge
645+
646+
When <<persistence-operations,`merge()`>> is used with cascading, that is, when the `merge()` operation is applied to a root entity with associations mapped `cascade=MERGE`, Hibernate issues a single `select` statement to retrieve the current database state associated with the entity and its associated entities.
647+
In certain circumstances, this query might be suboptimal.
648+
However, this query does not occur if the root entity was already loaded into the persistence context before `merge()` is called.
649+
650+
Therefore, we may gain control over the way state is loaded before a `merge()` just by calling `find()` before calling `merge()`.
651+
652+
[source,java]
653+
----
654+
Book book = ... ;
655+
var graph = session.createEntityGraph(Book.class);
656+
graph.addSubgraph(Book_.chapters); // Book.chapters mapped cascade=MERGE
657+
entityManager.find(graph, book.getIsbn()); // force loading of the book
658+
entityManager.merge(book);
659+
----
660+
661+
When merging multiple root entities, `findMultiple()` may be used instead of `find()`.
662+
663+
TIP: In some cases, `merge()` is much less efficient than the `upsert()` operation of <<stateless-sessions,`StatelessSession`>>.
664+
643665
[[flush]]
644666
=== Flushing the session
645667

0 commit comments

Comments
 (0)