Understanding MyBatis Initialization: Configuration Creation and Design Patterns
This article explains the complete MyBatis initialization process, detailing how the XML configuration file is parsed into a Configuration object, how SqlSessionFactory and SqlSession are built, and highlights the Builder design pattern used throughout the setup, with code examples for manual configuration loading.
For any framework, initialization involves loading runtime configuration; MyBatis is no exception. This article walks through what MyBatis does during initialization, how it creates the Configuration object from an XML file, and how the resulting SqlSessionFactory and SqlSession are used.
1. What MyBatis Initialization Does
MyBatis loads configuration information such as properties, settings, type aliases, type handlers, object factories, plugins, environments, transaction managers, and data sources. All of these are stored in an org.apache.ibatis.session.Configuration object whose structure mirrors the XML configuration.
After the configuration is loaded, MyBatis can perform database operations.
XML‑based configuration: all settings are placed in mybatis‑config.xml and parsed into the internal Configuration object.
Java‑API configuration: developers manually create a Configuration instance and set properties programmatically.
2. Creating the Configuration Object from an XML File
The following code shows the typical usage:
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List list = sqlSession.selectList("com.foo.bean.BlogMapper.queryAllBlogInfo");The SqlSessionFactoryBuilder reads the input stream, creates an XMLConfigBuilder , parses the XML, and returns a fully populated Configuration object.
The parsing steps are:
Call SqlSessionFactoryBuilder.build(inputStream) .
Create an XMLConfigBuilder with the input stream.
Invoke XMLConfigBuilder.parse() to obtain a Configuration .
Use the Configuration to build a DefaultSqlSessionFactory .
Return the DefaultSqlSessionFactory to the client.
The source code of SqlSessionFactoryBuilder (simplified) is:
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
Configuration config = parser.parse();
return build(config);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try { inputStream.close(); } catch (IOException ignored) {}
}
}
private SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}During parsing, the builder processes child nodes such as properties , typeAliases , plugins , objectFactory , settings , environments , databaseIdProvider , typeHandlers , and mappers . The environments element is handled as follows:
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
if (isSpecifiedEnvironment(id)) {
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder envBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(envBuilder.build());
}
}
}
}
private boolean isSpecifiedEnvironment(String id) {
if (environment == null) throw new BuilderException("No environment specified.");
if (id == null) throw new BuilderException("Environment requires an id attribute.");
return environment.equals(id);
}The Environment class contains a static inner Builder that follows the Builder pattern, allowing flexible construction of environment objects.
3. Manually Loading XML to Create Configuration and SqlSessionFactory
Developers can also parse the XML manually:
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, null, null);
Configuration configuration = parser.parse();
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
SqlSession sqlSession = sqlSessionFactory.openSession();
List list = sqlSession.selectList("com.foo.bean.BlogMapper.queryAllBlogInfo");4. Design Patterns Involved
The initialization heavily relies on creational design patterns, especially the Builder pattern.
Builder Pattern for SqlSessionFactory
Because the constructor parameters for SqlSessionFactory can vary, a separate builder isolates the construction logic from the representation.
Builder Pattern for Environment Objects
The Environment class uses an inner Builder to assemble the environment’s id, transaction factory, and data source before creating an immutable Environment instance.
These patterns make the initialization process modular, extensible, and easier to maintain.
Overall, the article provides a detailed walkthrough of MyBatis initialization, the transformation of XML configuration into runtime objects, and the design patterns that facilitate this process.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.