How does Hibernate Distinguish Between Transient (i.e. newly instantiated) and Detached Objects

Hibernate uses the “version” property, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Hibernate uses the concept of entity state to distinguish … Read more

When does an Object Become Detached

myCar” is a persistent object at this stage. Session session1 = sessionFactory.openSession(); Car myCar = session1.get(Car.class, carId); session1.close(); once the session is closed “myCar” becomes a detached objectyou can now pass the “myCar” object all the way upto the presentation tier. It can be modified without any effect to your database table. myCar.setColor(“Red”); //no effect … Read more

What are the Benefits of Detached Objects

Pros: When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and … Read more

Explain Hibernate Object States? Explain Hibernate Objects Life Cycle

Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects  synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List  etc or define your own synchronization points with … Read more

What is a Session? Can you Share a Session Object Between Different Threads

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily … Read more