Hibernate Interview Questions

This section focuses on the interview questions and answers in the Hibernate stream. These hibernate questions will improve your knowledge about how and why certain things are done in the hibernate world.

In Hibernate, the most common used object is ‘Session’, can you explain what a session is? Is there a way by which you can share a session object between different threads?

Session is nothing but a light weight and a non-threadsafe object 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 (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession( ) method.

public class HibernateUtility {
public static final ThreadLocal local = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
return session;

It is also vital that you close your session after your unit of work completes. You cannot share it between threads.

Explain about SessionFactory in Hibernate ? Is SessionFactory thread-safe object?

SessionFactory is Hibernate’s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration( ).configure( ).buildSessionfactory( );

What are the different object states in hibernate ?

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 session.flush(), transaction.commit() calls). If you remove an item from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.

READ  Hibernate in Web Application

Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save( ), session.persist( ) etc.

In Hibernate when does an object become detached ?

Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId);      //”myCar” is a persistent object at this stage.
session1.close();     //once the session is closed “myCar” becomes a detached object

you 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 on the database

When you are ready to persist this change to the database, it can be reattached to another session as shown below:

Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
tx.commit();  //change is synchronized with the database.
session2.update(myCar);  //detached object ”myCar” gets re-attached

Explain the pros and cons of detached objects?

The pros of detached objects are – 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 later on re-attached to a new transaction via another session.

READ  Caching Objects in Hibernate

The cons of detached objects are – When working with detached objects is quite cumbersome, and it is better not to clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because – the objects hang around in Hibernate’s cache anyway.Also from pure rich domain driven design perspective, it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.

Explain the mechanism by which you can distinguish between transient (i.e. newly instantiated) and detached objects in Hibernate ?

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.You can create your own strategy with Interceptor.isUnsaved( ). When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.


Hope these hibernate interview questions have helped you to improve your knowledge in hibernate. We wish you all the best for your job interviews