Hibernate / MyBatis Interview questions
What is the difference between SqlSessionFactory and SqlSessionFactoryBuilder?
These are two distinct objects in MyBatis's bootstrap process, each with a narrow, single-purpose role: the builder constructs a factory from configuration, and the factory then produces sessions on an ongoing basis.
| SqlSessionFactoryBuilder | SqlSessionFactory |
| A one-time-use builder that reads configuration and produces a factory. | A long-lived object that produces SqlSession instances. |
| Not meant to be kept around after use. | Meant to be built once and reused for the application's lifetime. |
| Used once per configuration source, typically at startup. | Used repeatedly, once per unit of work, via openSession(). |
This split exists specifically so that the (comparatively expensive) work of parsing configuration and mapper XML happens exactly once, producing a reusable factory, rather than being repeated every time a new session is needed; the builder's job is finished the moment it produces the factory, while the factory's job continues for as long as the application runs.
In a Spring or Spring Boot application, this distinction is mostly invisible to application code, since MyBatis-Spring's SqlSessionFactoryBean handles invoking the builder and registering the resulting factory as a Spring bean automatically during application startup.
More Related questions...