Hibernate / MyBatis Interview questions
What is a SqlSessionFactory in MyBatis?
A SqlSessionFactory is the central factory object responsible for creating SqlSession instances, built once from MyBatis's configuration (data source settings, mapper registrations, type handlers) and then reused for the lifetime of the application, rather than being recreated for every database interaction.
String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
Because building a SqlSessionFactory involves parsing configuration and mapper XML files — a comparatively expensive, one-time operation — the standard MyBatis pattern is to construct exactly one SqlSessionFactory per application (or per database, if working with multiple databases) at startup, and keep it around as a long-lived singleton rather than rebuilding it repeatedly.
In a Spring or Spring Boot application, this construction is handled automatically by MyBatis-Spring (or MyBatis-Spring-Boot-Starter's auto-configuration), which builds and registers a SqlSessionFactory bean from Spring-managed configuration, so application code typically never needs to call SqlSessionFactoryBuilder directly.
More Related questions...