配置
<environments default="default">
<environment id="default">
<!-- 事务类型 -->
<transactionManager type="JDBC"/>
<!-- 数据源类型 -->
<dataSource type="POOLED">
<!-- 数据库连接基本信息 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/mybatis_demo01?useUnicode=true&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
XMLConfigBuilder#environmentsElement
- 只解析和 environments-default 相同的 environment 配置节点
- 可以在 XMLConfigBuilder 构造函数传入 environment 覆盖默认的 default
private void environmentsElement(XNode context) throws Exception {
if (context == null) {
return;
}
// 构建函数时可写入,默认为 null
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
// 只解析和 environment 名称相同的部分,不是全部解析 & 动态切换
if (isSpecifiedEnvironment(id)) {
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
break;
}
}
}