MyBatis-03-environment

YangDanMua發表於2024-04-16

配置

<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;
    }
  }
}