How to identify an object is transient or detached in hibernate?

前端 未结 5 814
無奈伤痛
無奈伤痛 2021-01-01 16:04

I know that transient instance means the instance is newly created and its corresponding row does not exist in the database where as detached instance has corresponding entr

5条回答
  •  心在旅途
    2021-01-01 17:05

    As others said, org.hibernate.Session.contains(Object) may be used in Hibernate to know if an entity instance is attached or detached. Regarding the transient state, the best that could be done I think is what org.hibernate.Session.saveOrUpdate(Object) (by virtue of org.hibernate.persister.entity.AbstractEntityPersister.isTransient(Object, SessionImplementor)) does, that is:

    • if the entity has no @Id property, it's always considered transient
    • if the entity has an @Id property value which is null, it's always considered transient
    • if the entity has an @Id property value which is equal to the configured unsaved-value, then it's considered transient (only applies to XML mapping, I think it's somewhat deprecated, see here)
    • if it has a @Version property whose value is the one of a newly created instance (that is, it's a null Long, or Date, etc.), then it's considered transient

    Hence, I think that, for entities without a generated id, looking at the @Version property is the way to go. If there's no such property, Hibernate itself in saveOrUpdate makes a SELECT query against the database to determine whether the entity instance is transient or not, to determine if it should do an INSERT or an UPDATE respectively.

    See Hibernate manual (as an example, 4.3 one here).

提交回复
热议问题