The configuration file, element by element
mybatis-config.xml is small but dense. A handful of settings quietly change how
your queries behave, and knowing which ones will save you from a very confusing bug report.
The full skeleton
Every element is optional except environments and mappers (and even
those disappear under Spring Boot). Order is mandatory — the DTD enforces it.
<configuration> <properties/> <!-- 1. externalised values --> <settings/> <!-- 2. runtime behaviour flags --> <typeAliases/> <!-- 3. short names for classes --> <typeHandlers/> <!-- 4. Java type <-> JDBC type --> <objectFactory/> <!-- 5. how results are instantiated --> <objectWrapperFactory/> <reflectorFactory/> <plugins/> <!-- 6. interceptors --> <environments/> <!-- 7. tx manager + data source --> <databaseIdProvider/> <!-- 8. multi-vendor SQL --> <mappers/> <!-- 9. where the statements live --> </configuration>
1 · properties
Keeps credentials out of the file and lets you swap values per environment. Values resolve in a defined precedence order, which is worth memorising.
<properties resource="db.properties">
<!-- inline defaults, lowest precedence -->
<property name="db.poolMaximumActiveConnections" value="20"/>
</properties>
<!-- used later like this -->
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</dataSource>
# resolved second — overrides the inline <property> defaults db.driver=org.postgresql.Driver db.url=jdbc:postgresql://localhost:5432/shop db.username=shop_app db.password=change-me
| Precedence | Source |
|---|---|
| 1 (wins) | Properties passed programmatically to SqlSessionFactoryBuilder.build(reader, props) |
| 2 | resource or url attribute of <properties> |
| 3 | Nested <property> elements |
Enable org.apache.ibatis.parsing.PropertyParser.enable-default-value and you can
write ${db.port:5432}. It is off by default for backwards compatibility.
2 · settings — the ones that matter
There are roughly thirty settings. These are the ones that change observable behaviour in real projects; the rest you will likely never touch.
| Setting | Default | What it really does |
|---|---|---|
mapUnderscoreToCamelCase | false |
Maps user_name to userName automatically. Turn it on in
every new project — it removes most trivial result maps. |
cacheEnabled | true |
Global switch for the second level cache. The first level cache is not
affected (see localCacheScope). |
localCacheScope | SESSION |
STATEMENT disables the first level cache between statements — useful
when another process writes to your tables mid-transaction. |
lazyLoadingEnabled | false |
Makes nested selects lazy. Requires a bytecode provider on the classpath. |
aggressiveLazyLoading | false (since 3.4.1) |
When true, touching any property loads all lazy associations. Leave it off. |
defaultExecutorType | SIMPLE |
REUSE caches prepared statements; BATCH queues updates.
See chapters 6 and 10. |
defaultStatementTimeout | unset | Seconds before a statement is cancelled. Always set it in production. |
defaultFetchSize | unset | JDBC fetch size hint. Critical for large result streaming on PostgreSQL/MySQL. |
callSettersOnNulls | false |
When false, a NULL column never calls the setter — so map keys are
missing entirely for Map results. Turn on if you return maps. |
returnInstanceForEmptyRow | false |
Return an empty object instead of null when every column is NULL
(common with outer joins). |
autoMappingBehavior | PARTIAL |
NONE, PARTIAL (no nested), FULL. FULL can map
columns into nested objects unexpectedly. |
autoMappingUnknownColumnBehavior | NONE |
Set to WARNING during development to catch column typos immediately. |
jdbcTypeForNull | OTHER |
Oracle needs NULL here or inserting a null parameter throws
invalid column type. |
logImpl | auto-detected | SLF4J, LOG4J2, STDOUT_LOGGING, NO_LOGGING. |
useGeneratedKeys | false |
Global default for insert key retrieval; usually set per statement instead. |
safeRowBoundsEnabled | false |
Guards against in-memory RowBounds paging on nested result maps. |
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="cacheEnabled" value="false"/> <setting name="defaultStatementTimeout" value="30"/> <setting name="defaultFetchSize" value="200"/> <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/> <setting name="callSettersOnNulls" value="true"/> <setting name="logImpl" value="SLF4J"/> </settings>
The second level cache is per-JVM. In a multi-instance deployment it will serve stale data unless you plug in a distributed provider. Start with it off and enable it deliberately, per namespace — chapter 9 explains exactly when it is safe.
3 · typeAliases
Replaces com.bitsnippets.shop.domain.User with User in every
resultType. Scanning a package is almost always what you want.
<typeAliases> <!-- explicit --> <typeAlias alias="User" type="com.bitsnippets.shop.domain.User"/> <!-- or scan: every class gets its simple name, lower-cased first letter also works --> <package name="com.bitsnippets.shop.domain"/> </typeAliases>
You can also override the generated alias with an annotation on the class itself, which keeps the config file untouched:
@Alias("CustomerOrder")
public class Order { /* ... */ }
MyBatis pre-registers aliases for the usual suspects — you never need to declare these:
_byte _long _short _int _integer _double _float _boolean string byte long short int integer double float boolean date decimal bigdecimal biginteger object map hashmap list arraylist collection iterator
4 · typeHandlers
A TypeHandler converts between a Java type and a JDBC type in both directions.
Built-ins cover primitives, wrappers, String, BigDecimal, the
java.time types, arrays, blobs and enums (by name). Register your own here —
the implementation is covered in chapter 12.
<typeHandlers>
<typeHandler handler="com.bitsnippets.shop.handler.JsonTypeHandler"
javaType="com.bitsnippets.shop.domain.Metadata"
jdbcType="OTHER"/>
<!-- or scan a package -->
<package name="com.bitsnippets.shop.handler"/>
</typeHandlers>
The default handler stores enum.name() as a string. To store the ordinal
instead, register EnumOrdinalTypeHandler for that specific enum — but be aware
that reordering the enum constants then silently corrupts existing rows.
6 · plugins
Interceptors wrap Executor, ParameterHandler,
ResultSetHandler and StatementHandler. Declaration order is
significant: the last declared plugin is the outermost proxy.
<plugins>
<plugin interceptor="com.bitsnippets.shop.plugin.SlowQueryLogger">
<property name="thresholdMillis" value="250"/>
</plugin>
</plugins>
7 · environments
An environment bundles a transaction manager and a data source. You may declare several and pick one at build time — though in a Spring application you would use profiles instead and delete this section entirely.
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="poolMaximumActiveConnections" value="10"/>
<property name="poolMaximumIdleConnections" value="5"/>
<property name="poolTimeToWait" value="20000"/>
</dataSource>
</environment>
<environment id="container">
<transactionManager type="MANAGED">
<property name="closeConnection" value="false"/>
</transactionManager>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jdbc/shopDS"/>
</dataSource>
</environment>
</environments>
Transaction manager types
| Type | Behaviour | Use when |
|---|---|---|
JDBC | Uses the connection's own commit/rollback; MyBatis owns the transaction. | Standalone applications |
MANAGED | Does nothing — commit and rollback are no-ops; the container owns the transaction. | JEE containers, or Spring (which supplies its own) |
Data source types
| Type | Behaviour |
|---|---|
UNPOOLED | Opens and closes a connection per request. Fine for migrations and tests, disastrous under load. |
POOLED | MyBatis' own simple pool. Adequate for small apps and samples. |
JNDI | Looks up a container-managed DataSource. |
The built-in POOLED source has no leak detection, no metrics and no
connection validation strategy worth the name. Under Spring Boot you get HikariCP for
free; standalone, build the SqlSessionFactory programmatically and hand it a
HikariDataSource.
HikariConfig hikari = new HikariConfig();
hikari.setJdbcUrl("jdbc:postgresql://localhost:5432/shop");
hikari.setUsername("shop_app");
hikari.setPassword(System.getenv("DB_PASSWORD"));
hikari.setMaximumPoolSize(20);
hikari.setLeakDetectionThreshold(20_000);
DataSource dataSource = new HikariDataSource(hikari);
Environment environment =
new Environment("prod", new JdbcTransactionFactory(), dataSource);
Configuration configuration = new Configuration(environment);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setDefaultStatementTimeout(30);
configuration.addMapper(UserMapper.class);
configuration.getTypeAliasRegistry().registerAliases("com.bitsnippets.shop.domain");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);
8 · databaseIdProvider
Lets one mapper carry vendor-specific variants of a statement. MyBatis picks the statement
whose databaseId matches, falling back to the one without an id.
<databaseIdProvider type="DB_VENDOR"> <property name="MySQL" value="mysql"/> <property name="PostgreSQL" value="postgres"/> <property name="Oracle" value="oracle"/> <property name="H2" value="h2"/> </databaseIdProvider>
<select id="findPage" resultType="User" databaseId="oracle">
SELECT * FROM (
SELECT a.*, ROWNUM rnum FROM (
SELECT id, user_name FROM app_user ORDER BY id
) a WHERE ROWNUM <= #{offset} + #{limit}
) WHERE rnum > #{offset}
</select>
<select id="findPage" resultType="User">
SELECT id, user_name FROM app_user ORDER BY id
LIMIT #{limit} OFFSET #{offset}
</select>
9 · mappers
Four ways to register statements. Mixing them is legal but confusing; pick one per project.
<mappers> <!-- 1. classpath resource — most common with XML mappers --> <mapper resource="com/bitsnippets/shop/mapper/UserMapper.xml"/> <!-- 2. absolute URL — rare, useful for externally managed SQL --> <mapper url="file:///etc/shop/sql/OrderMapper.xml"/> <!-- 3. a single interface (annotations, or XML found beside it) --> <mapper class="com.bitsnippets.shop.mapper.ProductMapper"/> <!-- 4. scan a package — best for large projects --> <package name="com.bitsnippets.shop.mapper"/> </mappers>
Using both <package> and an explicit <mapper resource> for
the same namespace throws “Result Maps collection already contains value for …” at
startup. The scan already found the XML; delete the explicit entry.
What changes under Spring Boot
The starter builds the Configuration from application.yml, so the XML
file usually disappears. The mapping between the two is mechanical:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/shop
username: shop_app
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 20
mybatis:
type-aliases-package: com.bitsnippets.shop.domain
mapper-locations: classpath:com/bitsnippets/shop/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
default-statement-timeout: 30
cache-enabled: false
auto-mapping-unknown-column-behavior: WARNING
Note the naming: XML uses camelCase (mapUnderscoreToCamelCase), YAML uses
kebab-case (map-underscore-to-camel-case). Chapter 11 covers the rest.
Which setting stops SELECTs inside one session from returning stale
rows written by another transaction?
cacheEnabled only controls the second level cache. Repeated identical queries
inside a single session are served from the first level cache, whose scope is governed by
localCacheScope. Setting it to STATEMENT clears it after every
statement.
Next
Configuration done. Chapter 4 opens the mapper XML itself: statement types, attributes,
reusable fragments and the #{} versus ${} distinction that decides
whether your application is SQL-injectable.