Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining an object state

Tags:

java

hibernate

Does hibernate provide a method that returns an object's state (transient, persistent, detached)?

like image 474
Maurice Perry Avatar asked May 14 '09 07:05

Maurice Perry


2 Answers

see Javadoc Hibernate Session and check the methods

  • contains - Check if this instance is associated with this Session.
  • getIdentifier - Return the identifier value of the given entity as associated with this session. Beware of the Exception that is thrown if the Entity is not associated, each Exception should be considered fatal and the Session should not be used after it
  • get - Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.

i would use 'get' and furthermore check for changed values, after that its just an "saveOrUpdate" to persist or update (and re-attach) the actual object

like image 107
Michael Pralow Avatar answered Oct 05 '22 13:10

Michael Pralow


Session.contains tells you if an object is associated with the session. If it has no identifier, it's transient, if it has an identifier and associated with the session, persistent. Identifier but not associated with a session, detached.

If that doesn't help, consider rephrasing your question with more context, that is, why do you need to know the state of an object in the first place?

like image 38
Jörn Zaefferer Avatar answered Oct 05 '22 12:10

Jörn Zaefferer