Configuration and SqlSessionFactory
Harry
· 11 Sep 2026
· 9 views
mybatis-config.xml
The central configuration file declares environments, mappers and global settings.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/shop"/>
<property name="username" value="root"/>
<property name="password" value="secret"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/CustomerMapper.xml"/>
</mappers>
</configuration>Built With the XML Builder
String resource = "mybatis-config.xml";
InputStream input = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input);Using a Session
try (SqlSession session = factory.openSession()) {
CustomerMapper mapper = session.getMapper(CustomerMapper.class);
Customer c = mapper.findById(1L);
}Always close sessions. The try-with-resources pattern guarantees it.
Key Points
- mybatis-config.xml wires environments, data sources and mappers.
- SqlSessionFactoryBuilder reads the XML once to build the factory.
- SqlSessionFactory is thread-safe and should be created once.
- Sessions are cheap but must be closed; use try-with-resources.