Session and Transaction


Session and Transaction Interview with follow-up questions

1. What is a Session in Hibernate?

A Session in Hibernate is the primary runtime interface for performing persistence operations. It represents a single unit of work — a short-lived object typically opened at the start of a request and closed at the end.

Key characteristics:

  • First-level cache: the Session maintains an identity map. If you load the same entity by ID twice within one Session, the second call returns the cached instance without a database round-trip.
  • Dirty checking: Hibernate takes a snapshot of each entity's state when it is loaded. At flush time it compares current state to the snapshot and issues UPDATE statements only for changed fields.
  • Not thread-safe: never share a Session between threads.
  • Created from SessionFactory: SessionFactory is the heavyweight, thread-safe, application-scoped factory; Session is the lightweight, short-lived, request-scoped object.

In JPA terms, Session maps to EntityManager. In modern Spring Boot 3.x applications you inject EntityManager and call .unwrap(Session.class) only when Hibernate-specific features are needed:

@PersistenceContext
private EntityManager em;

// When Hibernate-specific API is needed:
Session session = em.unwrap(Session.class);

> Common interview follow-up: What is the difference between get() and load()? get() hits the database immediately and returns null if not found; load() returns a proxy and throws ObjectNotFoundException only when the proxy is accessed.

↑ Back to top

Follow-up 1

Can you explain the concept of a Session Factory?

A Session Factory in Hibernate is a thread-safe object that is used to create Session objects. It is typically created once during the application startup and shared by all threads. The Session Factory is responsible for managing the configuration settings, mapping metadata, and caching information required by Hibernate. It is also responsible for creating and managing database connections. The Session Factory is an expensive object to create, so it is recommended to create it once and reuse it throughout the application.

Follow-up 2

How does a Session differ from a Connection?

A Session in Hibernate is higher-level abstraction than a Connection. While a Connection represents a physical connection to the database, a Session represents a logical connection to the database. A Session manages the connection to the database and provides a higher-level API for interacting with the database, such as querying and manipulating objects. A Session can use multiple Connections internally to perform its operations.

Follow-up 3

What is the lifecycle of a Session?

The lifecycle of a Session in Hibernate consists of the following states:

  1. Transient: A Session is in the transient state when it is first created or after it has been closed. In this state, it is not associated with any database connection.
  2. Persistent: A Session becomes persistent when it is associated with a database connection. It can now be used to load, save, update, and delete objects in the database.
  3. Detached: A Session becomes detached when it is no longer associated with a database connection. It can still be used to read and modify objects, but it cannot perform database operations directly.
  4. Closed: A Session is closed when it is no longer needed. It releases any resources it holds, such as database connections and caches.

Follow-up 4

What happens if we don't close a Session?

If a Session is not closed properly, it can lead to resource leaks and performance issues. When a Session is not closed, it continues to hold the database connection and other resources, such as caches and temporary objects. This can result in a limited number of available connections and increased memory usage. It is important to always close a Session after using it to release the resources it holds. Hibernate provides the close() method to close a Session.

Follow-up 5

What are the different ways to obtain a Session in Hibernate?

There are several ways to obtain a Session in Hibernate:

  1. Using SessionFactory: The most common way is to obtain a Session from a Session Factory. The Session Factory provides the openSession() method to create a new Session.
  2. Using getCurrentSession(): If you are using Hibernate in a managed environment, such as Java EE or Spring, you can use the getCurrentSession() method to obtain a Session. This method returns a Session bound to the current thread or transaction.
  3. Using JPA EntityManager: If you are using JPA with Hibernate as the persistence provider, you can obtain a Session from the JPA EntityManager. The EntityManager provides the unwrap(Session.class) method to get the underlying Hibernate Session.
  4. Using HibernateUtil class: In some cases, you may use a custom utility class, such as HibernateUtil, to obtain a Session. This class typically manages the Session Factory and provides a static method to get a Session.

2. What is a Transaction in Hibernate?

A Transaction in Hibernate represents a unit of work on the database — a sequence of read and/or write operations that must all succeed or all be rolled back together.

ACID properties guaranteed by transactions:

  • Atomicity: all operations in the transaction succeed or none of them do.
  • Consistency: the database moves from one valid state to another.
  • Isolation: concurrent transactions are isolated from each other (degree depends on the isolation level).
  • Durability: once committed, changes survive system failures.

Native Hibernate API:

Session session = sessionFactory.openSession();
Transaction tx = null;
try {
    tx = session.beginTransaction();
    session.persist(order);
    tx.commit();
} catch (Exception e) {
    if (tx != null) tx.rollback();
    throw e;
} finally {
    session.close();
}

Spring Boot 3.x (preferred):

The @Transactional annotation on a service method handles begin, commit, and rollback automatically, eliminating the try/catch boilerplate:

@Transactional
public void saveOrder(Order order) {
    repository.save(order);
}

> Gotcha: By default, Spring only rolls back on unchecked exceptions (RuntimeException and Error). To roll back on a checked exception, use @Transactional(rollbackFor = MyCheckedException.class).

↑ Back to top

Follow-up 1

How does Hibernate handle transactions?

Hibernate provides built-in transaction management support. It can automatically manage transactions using the underlying transaction manager, such as JTA (Java Transaction API) or JDBC (Java Database Connectivity). Hibernate uses the concept of a session to manage transactions. When a session is opened, a new transaction is automatically started. Hibernate can commit or rollback the transaction based on the success or failure of the database operations.

Follow-up 2

What is the role of the Transaction interface?

The Transaction interface in Hibernate provides methods to control and manage transactions. It allows you to commit or rollback a transaction, set the transaction timeout, and check the transaction status. The Transaction interface is obtained from the current session using the session.getTransaction() method.

Follow-up 3

What is the difference between a local and a global transaction?

In Hibernate, a local transaction is specific to a single database connection or session. It is managed by the underlying transaction manager, such as JDBC. On the other hand, a global transaction involves multiple resources, such as multiple databases or message queues. It is managed by a distributed transaction coordinator, such as JTA. Global transactions provide atomicity and consistency across multiple resources.

Follow-up 4

How can we manage transactions in Hibernate?

Transactions in Hibernate can be managed in several ways:

  1. Programmatic Transaction Management: You can manually begin, commit, or rollback transactions using the Transaction interface.

  2. Declarative Transaction Management: You can use annotations or XML configuration to define transaction boundaries. Hibernate will automatically manage the transactions based on the configuration.

  3. Spring Framework Integration: If you are using the Spring Framework, you can leverage its transaction management capabilities to manage transactions in Hibernate.

Follow-up 5

What happens if a transaction fails in Hibernate?

If a transaction fails in Hibernate, the changes made within the transaction are rolled back. This means that any database operations performed within the transaction will be undone, and the database will be restored to its previous state. Hibernate will also throw an exception indicating the cause of the transaction failure, allowing you to handle the error appropriately.

3. How does Hibernate manage Sessions and Transactions?

Hibernate manages Sessions and Transactions through the interplay of SessionFactory, Session, and either its native Transaction API or Spring's transaction management.

SessionFactory (maps to JPA's EntityManagerFactory):

  • Created once at application startup — expensive to build, thread-safe, application-scoped.
  • In Spring Boot 3.x it is created automatically from application.properties settings; you never instantiate it manually.

Session lifecycle:

  1. A Session is obtained from the SessionFactory (or from Spring's current transaction context via @PersistenceContext EntityManager).
  2. Persistence operations are performed within the Session.
  3. At flush time (typically before a query or at commit), dirty-checked changes are written to the database.
  4. The Session is closed, releasing the JDBC connection back to the pool.

Transaction lifecycle (Spring Boot):

  • @Transactional on a service method tells Spring's PlatformTransactionManager to start a transaction before the method and commit (or roll back) after it returns.
  • Hibernate participates via HibernateTransactionManager or JpaTransactionManager.
  • Transaction propagation (e.g., REQUIRED, REQUIRES_NEW) and isolation level are configurable per annotation.

Current-session context: Hibernate's getCurrentSession() returns the Session bound to the current transaction context, making it safe to call from multiple methods in the same transaction without passing the Session around.

↑ Back to top

Follow-up 1

What is the role of the SessionFactory in managing Sessions?

The SessionFactory is responsible for creating and managing Sessions in Hibernate.

When an application starts, Hibernate creates a SessionFactory object. The SessionFactory is a thread-safe object that can be shared across multiple threads and transactions.

The SessionFactory is used to obtain Session objects. Sessions are used to perform database operations such as saving, updating, and deleting objects. The SessionFactory also caches metadata about the mapping between Java objects and database tables, which improves performance by avoiding repeated database queries for the same information.

The SessionFactory should be created once during application startup and reused throughout the application's lifetime.

Follow-up 2

What is the difference between getCurrentSession() and openSession() methods?

In Hibernate, there are two methods for obtaining a Session: getCurrentSession() and openSession().

The getCurrentSession() method is used to obtain the current Session associated with the current thread. It is typically used in applications that use a single Session per thread model. The getCurrentSession() method automatically manages the lifecycle of the Session and provides transactional support.

The openSession() method is used to explicitly open a new Session. It allows more control over the Session's lifecycle and transaction management. The openSession() method requires manual management of the Session and transaction, and it is typically used in applications that require fine-grained control over Sessions and transactions.

Follow-up 3

How does Hibernate ensure data consistency during transactions?

Hibernate ensures data consistency during transactions through the use of the Transaction Manager.

When a transaction is started, Hibernate obtains a database connection and associates it with the current Session. All database operations performed within the transaction are executed on this connection.

Hibernate uses the underlying database's transaction management capabilities to ensure data consistency. It uses the ACID (Atomicity, Consistency, Isolation, Durability) properties of transactions to guarantee that all database operations within a transaction are atomic and consistent.

If a transaction fails, Hibernate rolls back the transaction, undoing any changes made to the database. This ensures that the database remains in a consistent state.

Follow-up 4

What is the role of the Transaction Manager?

The Transaction Manager is responsible for managing transactions in Hibernate.

The Transaction Manager is used to start, commit, and roll back transactions. It ensures that all database operations within a transaction are atomic and consistent.

In Hibernate, the Transaction Manager is typically provided by the underlying application server or framework. It abstracts away the low-level details of transaction management and provides a high-level API for managing transactions.

The Transaction Manager works in conjunction with the SessionFactory and the underlying database's transaction management capabilities to ensure data consistency during transactions.

Follow-up 5

What is the impact of a failed transaction on the Session?

If a transaction fails in Hibernate, the Session is automatically cleared and any changes made to the Session are discarded.

When a transaction fails, Hibernate rolls back the transaction, undoing any changes made to the database. This ensures that the database remains in a consistent state.

After a transaction failure, the Session is no longer usable. Any subsequent database operations performed on the Session will throw an exception.

To continue working with the database, a new Session must be obtained from the SessionFactory.

4. What are the different states of a Session in Hibernate?

Note: This question is often asked as "What are the different states of a Hibernate object?" — the answer describes entity lifecycle states, not session states. A Session itself is either open or closed.

The four entity (object) states in Hibernate:

  1. Transient: the object has been created with new but has never been associated with a Session. It has no database representation and no identifier value assigned by Hibernate. It is a plain Java object unknown to the persistence context.

  2. Persistent (Managed): the object is associated with an open Session and has a corresponding row in the database. Hibernate tracks all changes — at flush time any modifications are automatically synchronized to the database via UPDATE statements (dirty checking). Obtained via persist(), find(), merge(), or by loading through a query.

  3. Detached: the object was once persistent but its Session has been closed (or it was explicitly evicted with evict()/detach()). It still has a valid database identifier but changes are no longer tracked. To make changes persist, re-attach with merge().

  4. Removed: remove() has been called on a persistent entity. Hibernate will issue a DELETE at flush time. The object should not be used after this point.

State transition summary:

new keyword  →  Transient
persist()    →  Persistent
session close / evict()  →  Detached
merge()      →  Persistent (from Detached)
remove()     →  Removed
↑ Back to top

Follow-up 1

What is a disconnected Session?

A disconnected Session is a Session that was opened, used, and then disconnected from the database. It can be reconnected to the database with a new database connection and used again. This is useful in long-running units of work, where the database resources have to be released, but the application may continue to process the objects.

Follow-up 2

What happens when a Session is closed?

When a Session is closed, it is disconnected from the database. All the persistent objects that were associated with it become detached objects. These objects can be reattached to a new Session later.

Follow-up 3

What is the difference between a Session and a Stateless Session?

A Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create, read, update and delete persistent objects.

A Stateless Session, on the other hand, is a type of Session that does not implement a first-level cache nor interact with any second-level or query cache. It does not implement transactional write-behind or automatic dirty checking, nor does it implement session-level write operations. For certain bulk operations, a Stateless Session may perform better than a regular Session.

Follow-up 4

How can we reattach a detached instance to a Session?

A detached instance can be reattached to a Session using the update() method or merge() method. The update() method should be used if you are sure that the Session does not contain an already persistent instance with the same identifier, and the merge() method should be used if you want to merge your modifications at any time without considering the state of the Session.

Follow-up 5

What is the impact of flushing a Session?

Flushing a Session forces Hibernate to synchronize the in-memory state of the Session with the database. Normally, Hibernate will do this automatically for you, but you can also control the process manually if needed. This is typically necessary when you're dealing with large amounts of data and need to manage memory efficiently.

5. How can we control transactions in Hibernate?

Transaction control in Hibernate can be exercised in two ways, depending on whether you are using the native API or Spring.

1. Native Hibernate API (standalone / without Spring):

Session session = sessionFactory.openSession();
Transaction tx = null;
try {
    tx = session.beginTransaction();

    Product p = session.get(Product.class, 1L);
    p.setPrice(new BigDecimal("29.99"));

    tx.commit();  // dirty-checked changes flushed and committed
} catch (Exception e) {
    if (tx != null && tx.isActive()) {
        tx.rollback();
    }
    throw e;
} finally {
    session.close();
}

2. Spring's @Transactional (recommended in Spring Boot 3.x):

@Service
public class ProductService {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public void updatePrice(Long id, BigDecimal price) {
        Product p = em.find(Product.class, id);
        p.setPrice(price);
        // no explicit commit — Spring commits when the method returns
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void auditChange(String msg) { ... }

    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void criticalOperation() { ... }
}

Key @Transactional attributes:

  • propagation: REQUIRED (default), REQUIRES_NEW, NESTED, etc.
  • isolation: maps to JDBC isolation levels.
  • rollbackFor: additional exception types that trigger rollback.
  • readOnly = true: hint to optimize read-only transactions.
↑ Back to top

Follow-up 1

What is the purpose of the beginTransaction() method?

The beginTransaction() method is used to start a new transaction. It initializes the transaction context and associates it with the current Session.

Follow-up 2

What is the difference between commit() and rollback() methods?

The commit() method is used to save the changes made during the transaction and make them permanent. It ends the transaction by flushing the changes to the database.

The rollback() method is used to discard the changes made during the transaction and revert the database to its previous state. It ends the transaction without saving any changes.

Follow-up 3

How can we set the isolation level for a transaction?

The isolation level for a transaction can be set using the setTransactionIsolation() method of the Connection object. Hibernate provides a way to access the underlying JDBC Connection object through the Session object. By obtaining the Connection object, you can set the isolation level using the setTransactionIsolation() method.

Follow-up 4

What is the impact of setting a transaction as read-only?

Setting a transaction as read-only indicates that the transaction will only read data from the database and will not make any modifications. This allows Hibernate to optimize the transaction by skipping certain checks and operations that are only necessary for write transactions. It can improve performance and reduce the chances of conflicts or deadlocks.

Follow-up 5

How can we handle exceptions during transactions?

Exceptions during transactions can be handled using try-catch blocks. You can wrap the transaction code in a try block and catch any exceptions that occur. In the catch block, you can handle the exception appropriately, such as rolling back the transaction or logging the error. Additionally, Hibernate provides a way to define exception handlers using the ExceptionHandler interface. You can implement this interface and register the handler with the SessionFactory to handle specific types of exceptions.

Live mock interview

Mock interview: Session and Transaction

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.