问题
Quote from documentation:
detached
the entity has an associated identifier, but is no longer associated with a persistence context (usually because the persistence context was closed or the instance was evicted from the context)
Does it mean that hibernate keep references to all objects that have been ever persistence? But then it would cause memory lick.
Or it means that entity has an id that corresponds to an entity in a database then it would lead to two conclusions: 1) It can be checked only querying a database. 2) A detached entity can become transient if some one third would delete the entity from the database.
回答1:
When an entity is first created in application using the new() operator, it remains in transient state.It can move to Persistent state when you associate it with a session by calling Session.save() method. When you close() the session or evict() that object from session, it moves to detached state. You can again move a detached object to Persistent state by calling Session.update() or Session.saveOrUpdate() method.
回答2:
I didn't find anything in the documentation regarding this, but I believe it does track detached entities ... for example, According to JPA specs, you have the case when an entity was fetched (but its lazy relations are not) ... If you detach this entity then merge it again , It considers the the relations unloaded, but if you set the relation to null, then after merging it will be also set to null ... so how will it differentiate if it doesn't keep record of the detached ... there are also some scenarios in the cascade.MERGE behavior that might tell that it keeps record of the previously detached entities .... again this is what I expect, no documentation there
来源:https://stackoverflow.com/questions/48426067/how-hibernate-differs-transient-and-detached-entities