Skip to content

Commit 7f8fbb5

Browse files
committed
add explanation of whole transient vs detached stuff
should have had this from the start
1 parent c4a668f commit 7f8fbb5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

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

+23
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,29 @@ A great deal of human suffering has resulted from users mismanaging the lifecycl
9595
We'll conclude by noting that whether a persistence context helps or harms the performance of a given unit of work depends greatly on the nature of the unit of work.
9696
For this reason Hibernate provides both stateful and stateless sessions.
9797

98+
[[transient-vs-detached]]
99+
=== Transient vs detached
100+
101+
Sometimes, Hibernate needs to be able to distinguish whether an entity instance is:
102+
103+
- a brand-new transient object the client just instantiated using `new`, or
104+
- a detached object, which previously belonged to a persistence context.
105+
106+
This is a bit of a problem, since there's no good way for Hibernate to just tag an entity with a Post-it saying "I've seen you before" that wouldn't have a negative impact on performance.
107+
108+
Therefore, Hibernate uses heuristics.
109+
The two most useful heuristics are:
110+
111+
1. If the entity has a <<generated-identifiers,generated identifier>>, the value of the id field is inspected: if the value currently assigned to the id field is the default value for the type of the field, then the object is transient; otherwise, the object is detached.
112+
2. If the entity has a <<version-attributes,version>>, the value of the version field is inspected: if the value currently assigned to the version field is the default value, or a negative number, then the object is transient; otherwise, the object is detached.
113+
114+
If the entity has neither a generated id, nor a version, Hibernate falls back to just doing something reasonable.
115+
116+
[WARNING]
117+
These heuristics aren't perfect.
118+
It's quite easy to confuse Hibernate by assigning a value to the id field or version field that makes a new transient instance look like it's detached.
119+
We therefore strongly discourage assigning values to fields annotated `@GeneratedValue` or `@Version` before passing an entity to Hibernate.
120+
98121
[[creating-session]]
99122
=== Creating a session
100123

0 commit comments

Comments
 (0)