Hibernate / MyBatis Interview questions
What is a SqlSession in MyBatis?
A SqlSession is the primary interface for executing SQL commands, retrieving mappers, and managing transactions in MyBatis, created from a SqlSessionFactory and representing a single, typically short-lived unit of work against the database.
try (SqlSession session = sqlSessionFactory.openSession()) { UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.selectUserById(1); session.commit(); }
Unlike the SqlSessionFactory, a SqlSession is not thread-safe and is not meant to be shared or kept open long-term — the standard pattern is opening one per request or unit of work, using it, and then closing it (commonly via try-with-resources, as shown above) rather than holding it open across multiple unrelated operations.
A SqlSession also owns the first-level (session-scoped) cache, so identical queries executed on the same session within the same transaction can be served from that cache rather than hitting the database again, which is one of several reasons sessions are meant to be short-lived and scoped tightly to a single logical operation rather than reused broadly across an application.
More Related questions...