Sobes.tech
Junior — Middle

Explain the working principle of sessions in Hibernate and their role in managing objects and transactions.

sobes.tech AI

Answer from AI

In Hibernate, a session (Session) is the primary interface for interacting with the database. It represents a context for working with objects, managing their states (new, managed, detached, deleted).

The session is responsible for:

  • Managing the lifecycle of objects: when an object is loaded from the database, it becomes managed, changes are tracked, and upon saving, they are translated into SQL queries.
  • First-level cache: the session stores objects in memory to avoid repeated database queries for the same object.
  • Transaction management: the session is opened, transactions are started and ended within it, ensuring atomicity of operations.

Example of using a session:

Session session = sessionFactory.openSession();
Transaction tx = null;
try {
    tx = session.beginTransaction();
    User user = session.get(User.class, userId); // loading an object
    user.setName("New Name"); // modifying the object
    session.update(user); // updating
    tx.commit();
} catch (Exception e) {
    if (tx != null) tx.rollback();
} finally {
    session.close();
}

Thus, the session is a key component for managing objects and transactions in Hibernate, ensuring data consistency and efficient interaction with the database.