Master MyBatis Global Config: Complete Guide to All Settings
This article provides a comprehensive walkthrough of MyBatis's mybatis-config.xml, detailing the top‑level configuration nodes, property handling, settings options, type aliases, type handlers, object factories, plugins, environment definitions, transaction managers, data source types, database ID providers, and mapper registrations, with concrete XML examples and priority rules.
Overview
MyBatis uses a single XML file ( mybatis-config.xml) to define global settings that affect all SQL sessions. The root element is configuration, and every other configuration node must be nested inside it.
Top‑Level Nodes
<properties></properties>
<!-- 属性 -->
<settings></settings>
<!-- 设置 -->
<typeAliases></typeAliases>
<!-- 配置别名 -->
<typeHandlers></typeHandlers>
<!-- 类型处理器 -->
<objectFactory></objectFactory>
<!-- 对象工厂 -->
<plugins></plugins>
<!-- 插件 -->
<environments default="">...</environments>
<!-- 环境配置 -->
<databaseIdProvider></databaseIdProvider>
<!-- 数据库厂商标识 -->
<mappers></mappers>
<!-- 映射器 -->There are nine top‑level nodes in total; each is explained below.
properties
Three ways to load properties:
Specify a resource attribute pointing to a .properties file.
Specify a url attribute pointing to a remote properties file.
Define <property> elements directly inside <properties>.
Only one of resource or url may be used; configuring both throws an exception (see image). After loading, properties can be referenced in other XML files via ${...}.
Properties Priority
Highest: properties passed programmatically to SqlSessionFactoryBuilder.build().
Second: properties loaded from resource or url.
Third: properties defined directly inside the properties element.
It is recommended to use a single method to avoid maintenance issues.
settings
The settings node contains many fine‑grained options that control MyBatis behavior. Each option is expressed as a <setting name="..." value="..."/> element. A representative sample:
<settings>
<setting name="cacheEnabled" value="false"/>
<setting name="lazyLoadingEnabled" value="false"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="multipleResultSetsEnabled" value="false"/>
<setting name="useColumnLabel" value="false"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="NONE"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="VARCHAR"/>
<setting name="logImpl" value="SLF4J"/>
<setting name="logPrefix" value="LONELY_WOLF_"/>
</settings>All possible settings are listed in the accompanying diagrams (kept as images).
typeAliases
Allows a short alias for a fully‑qualified Java class, reducing XML verbosity. Example:
<typeAlias alias="UserMapper" type="com.lonelyWolf.mybatis.mapper.UserMapper"/>Aliases can also be defined by package scanning:
<package name="com.lonelyWolf.mybatis.mapper"/>If a class is annotated with @Alias("lonely_wolf"), that name takes precedence over the default convention.
typeHandlers
Custom typeHandler implementations translate between Java types and JDBC types. Configuration examples:
<typeHandlers>
<typeHandler handler="com.example.MyHandler"/>
<package name="com.example.handlers"/>
</typeHandlers>MyBatis also provides a default mapping table (shown in the images).
objectFactory
The ObjectFactory creates result objects. The default simply calls the no‑arg constructor or a constructor matching the result mapping. Custom factories can be supplied by implementing the ObjectFactory interface.
plugins
Plugins can intercept execution points of mapped statements. Detailed usage is omitted here and will be covered in a separate article.
environments
Multiple environments (e.g., development, test, production) can be defined, but a single SqlSessionFactory selects only one at runtime. Example configuration:
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="..." value="..."/>
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>Key points:
Default environment ID (e.g., default="development").
Each environment has a unique ID.
Transaction manager configuration (type JDBC or MANAGED).
Data source configuration (type UNPOOLED, POOLED, or JNDI).
Transaction Managers
JDBC: MyBatis controls commit/rollback using the JDBC connection. MANAGED: Transaction lifecycle is delegated to an external container; not suitable for standalone MyBatis usage.
Data Sources
Three built‑in types:
UNPOOLED : Requires driver, url, username, password, and defaultTransactionIsolationLevel.
POOLED : Extends UNPOOLED with pool settings such as poolMaximumActiveConnections, poolMaximumIdleConnections, poolMaximumCheckoutTime, poolTimeToWait, poolPingQuery, poolPingEnabled, and poolPingConnectionsNotUsedFor.
JNDI : Uses a JNDI lookup; only initial_context (optional) and data_source are needed.
Custom Data Source
Implement DataSourceFactory and reference the fully‑qualified class name:
<dataSource type="com.example.CustomDataSource"/>databaseIdProvider
Enables vendor‑specific statements by assigning a databaseId to statements. Adding the provider is as simple as: <databaseIdProvider type="DB_VENDOR"/> MyBatis loads statements without a databaseId and those whose databaseId matches the current database; conflicting statements are resolved by preferring the matched one.
mappers
Mapper XML files can be registered in four ways:
Specify the XML file path via resource attribute.
Specify a URL via url attribute.
Reference the mapper interface class via class attribute (XML and interface must share the same name and directory).
Scan a package via <package name="..."/>.
When using class‑based registration, ensure the XML file and interface are co‑located and share the same name; otherwise Maven may fail to include the XML resources. The Maven build configuration snippet below forces inclusion of XML files:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>Conclusion
This guide serves as a reference handbook for MyBatis's global configuration file. It outlines each top‑level element, priority rules, and practical XML snippets, allowing developers to quickly locate the needed setting and understand its impact on the MyBatis runtime.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
