MyBatis-03-environment

配置

<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&amp;characterEncoding=utf8&amp;connectTimeout=1000&amp;socketTimeout=3000&amp;autoReconnect=true&amp;useSSL=false&amp;serverTimezone=UTC"/>
      <property name="username" value="root"/>
      <property name="password" value="123456"/>
    </dataSource>
  </environment>
</environments>

XMLConfigBuilder#environmentsElement

  1. 只解析和 environments-default 相同的 environment 配置节点
  2. 可以在 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;
    }
  }
}
posted @ 2024-04-16 22:42  YangDanMua  阅读(5)  评论(0编辑  收藏  举报