Hibernate / MyBatis Interview questions
Explain the lifecycle of a SqlSession?
A SqlSession moves through a defined, short-lived lifecycle: created from a SqlSessionFactory, used to execute one or more statements (typically within a single logical unit of work), and then explicitly closed, with the details of commit/rollback timing depending on whether it's being managed manually or via Spring.
In plain, non-Spring usage, a SqlSession defaults to non-auto-commit mode (unless openSession(true) is used), meaning an explicit commit() call is required for changes to persist, and the session must always be closed — typically via try-with-resources — to release its underlying database connection back to the pool, regardless of whether the operations succeeded or failed.
In a Spring-managed application, this entire lifecycle is handled transparently: SqlSessionTemplate (injected via MyBatis-Spring) manages session creation, commit/rollback (tied to Spring's own transaction boundaries, like @Transactional), and closing automatically, which is why application code using MyBatis-Spring rarely interacts with SqlSession lifecycle methods directly at all.
More Related questions...