美文网首页
Mybatis 文档篇 2.7:Configuration 之

Mybatis 文档篇 2.7:Configuration 之

作者: 兆雪儿 | 来源:发表于2019-03-22 11:12 被阅读0次

    1 Configuration Structure

    2 Environments

    MyBatis can be configured with multiple environments. This helps you to apply your SQL Maps to multiple databases for any number of reasons.
    MyBatis 可以配置多个环境。这将有助于你的 SQL 映射到多个数据库。有很多理由要这样做。

    For example, you might have a different configuration for your Development, Test and Production environments. Or, you may have multiple production databases that share the same schema, and you’d like to use the same SQL maps for both.
    例如,你的开发环境、测试环境、生产环境可能需要不同的配置。或者你可能有多个共享相同 Schema 的生产数据库想要使用相同的 SQL 映射。

    One important thing to remember though: While you can configure multiple environments, you can only choose ONE per SqlSessionFactory instance.So if you want to connect to two databases, you need to create two instances of SqlSessionFactory.
    重要:当你配置了多个环境,你只能为每个 SqlSessionFactory 实例选择一个环境。因此,如果你想要连接两个数据库,你需要创建两个 SqlSessionFactory 实例。

    2.1 Environment

    2.1.1 Build in Class

    To specify which environment to build, you simply pass it to the SqlSessionFactoryBuilder as an optional parameter. The two signatures that accept the environment are:
    指定要构建哪个环境,你只需要将其作为一个可选参数传递给 SqlSessionFactoryBuilder。可以接受环境配置的两个方法签名是:

    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment);
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, properties);
    

    If the environment is omitted, then the default environment is loaded, as follows:
    如果忽略了 environment 参数,那么默认的环境将被加载:

    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, properties);
    

    2.1.2 Build in XML

    The environments element defines how the environment is configured.
    environments 元素定义了环境配置。

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

    关键点:

    • The default Environment ID (e.g. default="development").
      默认的环境 ID(如 default="development")。

    • The Environment ID for each environment defined (e.g. id="development").
      为每个环境定义环境 ID(如 id="development")。

    • The TransactionManager configuration (e.g. type="JDBC")
      配置事务管理器 TransactionManager (如 type="JDBC")

    • The DataSource configuration (e.g. type="POOLED")
      配置数据源 DataSource(如 type="POOLED")

    The default environment and the environment IDs are self explanatory. Name them whatever you like, just make sure the default matches one of them.
    默认的环境和环境 ID 是自解释的。你可以对环境随意命名,只要确保默认的环境匹配其中之一。

    2.2 transactionManager

    2.2.1 默认的 transactionManager

    There are two TransactionManager types (i.e. type="[JDBC|MANAGED]") that are included with MyBatis:
    MyBatis 提供两种 TransactionManager 的类型:

    • JDBC – This configuration simply makes use of the JDBC commit and rollback facilities directly. It relies on the connection retrieved from the dataSource to manage the scope of the transaction.
      JDBC:直接使用了 JDBC 的提交和回滚设置。它依赖从数据库获取的连接来管理事务的作用域。

    • MANAGED – This configuration simply does almost nothing. It never commits, or rolls back a connection. Instead, it lets the container manage the full lifecycle of the transaction (e.g. a JEE Application Server context). By default it does close the connection. However, some containers don’t expect this, and thus if you need to stop it from closing the connection, set the "closeConnection" property to false.
      MANAGED:这个配置几乎什么也不做。它从来不提交或者回滚一个连接,而是让容器来管理事务的全生命周期(例如 JEE 应用服务器的上下文)。默认情况下,它是关闭连接的。然而,一些容器不希望这样做,因此如果你需要开启连接,设置 closeConnection 属性为 false 即可。

    <transactionManager type="MANAGED">
      <property name="closeConnection" value="false"/>
    </transactionManager>
    

    Node:If you are planning to use MyBatis with Spring there is no need to configure any TransactionManager because the Spring module will set its own one overriding any previously set configuration.
    注意:如果你计划使用 MyBatis + Spring,那就没有必要配置任何 TransactionManager,因为 Spring 模块中自带的事务管理器会覆盖前面的配置。

    2.2.2 自定义 transactionManager

    Neither of these TransactionManager types require any properties.However, they are both Type Aliases, so in other words, instead of using them, you could put your own fully qualified class name or Type Alias that refers to your own implementation of the TransactionFactory interface.
    这两种 TransactionManager 类型都不需要任何属性。它们都是类型别名,换句话说,你可以使用你自己的 TransactionFactory 接口的实现类的完全限定类名或类型别名来替代。

    public interface TransactionFactory {
      void setProperties(Properties props);
      Transaction newTransaction(Connection conn);
      Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);
    }
    

    Any properties configured in the XML will be passed to the setProperties() method after instantiation.
    任何在 XML 中定义的属性都会在实例化后传递给 setProperties() 方法。

    Your implementation would also need to create a Transaction implementation, which is also a very simple interface:
    你也需要创建一个 Transaction 接口的实现类,这个接口也很简单:

    public interface Transaction {
      Connection getConnection() throws SQLException;
      void commit() throws SQLException;
      void rollback() throws SQLException;
      void close() throws SQLException;
      Integer getTimeout() throws SQLException;
    }
    

    Using these two interfaces, you can completely customize how MyBatis deals with Transactions.
    使用这两个接口,你可以完全定制化地使用 MyBatis 的事务处理。

    2.3 dataSource

    The dataSource element configures the source of JDBC Connection objects using the standard JDBC DataSource interface.
    dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。

    Most MyBatis applications will configure a dataSource as in the example. However, it’s not required. Realize though, that to facilitate Lazy Loading, this dataSource is required.
    大多数的应用会像例子中那样配置一个 dataSource。但这也不是必须的。尽管如此,为了使用懒加载,dataSource 还是必要的。

    2.3.1 使用内置 DataSource

    There are three build-in dataSource types (i.e. type="[UNPOOLED|POOLED|JNDI]"):
    有三种内置的 dataSource 类型UNPOOLED、POOLED 和 JNDI。

    2.3.1.1 UNPOOLED

    This implementation of DataSource simply opens and closes a connection each time it is requested.
    作用:这种 DataSource 的实现仅仅负责每次被请求的时候打开和关闭一个连接。

    While it’s a bit slower, this is a good choice for simple applications that do not require the performance of immediately available connections.
    虽然有点慢,但对于数据库连接及时可用性要求不高的简单应用来说这是个很好的选择。

    Different databases are also different in this performance area, so for some it may be less important to pool and this configuration will be ideal.
    不同的数据库在此性能方面表现也是不一样的,所以对于某些数据库来说,使用连接池并没那么重要,因此这个配置对于这种情况是理想的。

    The UNPOOLED DataSource is configured with only five properties:
    UNPOOLED 类型的 DataSource 只有五个属性:

    • driver – This is the fully qualified Java class of the JDBC driver (NOT of the DataSource class if your driver includes one).
      driver:JDBC 驱动的 Java 类的完全限定名(不是驱动中可能包含的 DataSource 类)。

    • url – This is the JDBC URL for your database instance.
      url:数据库实例的 JDBC URL。

    • username – The database username to log in with.
      username:数据库的登录用户名

    • password - The database password to log in with.
      password:数据库的登录密码。

    • defaultTransactionIsolationLevel – The default transaction isolation level for connections.
      defaultTransactionIsolationLevel:连接默认的事务隔离级别。

    Optionally, you can pass properties to the database driver as well. To do this, prefix the properties with driver., for example:driver.encoding=UTF8.This will pass the property encoding, with the value UTF8, to your database driver via the DriverManager.getConnection(url, driverProperties) method.
    作为可选项,你也可以传递属性给数据库驱动。这样做的话,在属性前面需要加上 driver. 前缀,例如:driver.encoding=UTF8。这将通过 DriverManager.getConnection(url, driverProperties) 方法将值为 UTF-8 的属性 encoding 传递给你的数据库驱动。

    2.3.1.2 POOLED

    This implementation of DataSource pools JDBC Connection objects to avoid the initial connection and authentication time required to create a new Connection instance.
    作用:这种以连接池的形式来做的 DataSource 实现将 JDBC 连接对象组织起来,避免了创建新的连接实例时需要初始化连接和认证而浪费的时间。

    This is a popular approach for concurrent web applications to achieve the fastest response.
    这是一种使并发的 web 应用获取最快响应的流行的方式。

    In addition to the (UNPOOLED) properties above, there are many more properties that can be used to configure the POOLED datasource:
    除了上述提到的(UNPOOLED)属性以外,在 POOLED 方式的数据源中还有更多的属性可以被配置:

    • poolMaximumActiveConnections – This is the number of active (i.e. in use) connections that can exist at any given time. Default: 10
      poolMaximumActiveConnections :在任意时间可以活动的(即正在使用的)连接数。默认是10。

    • poolMaximumIdleConnections – The number of idle connections that can exist at any given time.
      poolMaximumIdleConnections :在任意时间可以存在的空闲连接数。

    • poolMaximumCheckoutTime – This is the amount of time that a Connection can be "checked out" of the pool before it will be forcefully returned. Default: 20000ms (i.e. 20 seconds)
      poolMaximumCheckoutTime :在被强制返回之前,池中连接被检出的时间。默认是 20000ms(即 20s)。

    • poolTimeToWait – This is a low level setting that gives the pool a chance to print a log status and re-attempt the acquisition of a connection in the case that it’s taking unusually long (to avoid failing silently forever if the pool is misconfigured). Default: 20000ms (i.e. 20 seconds)
      poolTimeToWait :这是个底层设置,如果获取连接花了相当长的时间,就会给连接池一个机会打印日志状态并重试获取连接(避免误配置的情况下一直悄悄的失败)。默认是 20000ms(即 20s)。

    • poolMaximumLocalBadConnectionTolerance – This is a low level setting about tolerance of bad connections got for any thread. If a thread got a bad connection, it may still have another chance to re-attempt to get another connection which is valid. But the retrying times should not more than the sum of poolMaximumIdleConnections and poolMaximumLocalBadConnectionTolerance. Default: 3 (Since: 3.4.5)
      poolMaximumLocalBadConnectionTolerance :这是个关于任意线程中容忍坏连接获取的底层设置。如果一个线程获取了一个坏连接,它将会有另外的机会重新尝试获取另外一个有效的连接。但是重试次数不能超过 poolMaximumIdleConnections 和 poolMaximumLocalBadConnectionTolerance 的总和。默认为3(从3.4.5开始)。

    • poolPingQuery – The Ping Query is sent to the database to validate that a connection is in good working order and is ready to accept requests. The default is "NO PING QUERY SET", which will cause most database drivers to fail with a decent error message.
      poolPingQuery :发送到数据库的侦测查询,用来检测连接是否正常且准备接受请求。默认设置是“NO PING QUERY SET”,该设置使得大多数的数据库驱动失败时抛出一个恰当的错误消息。

    • poolPingEnabled – This enables or disables the ping query. If enabled, you must also set the poolPingQuery property with a valid SQL statement (preferably a very fast one). Default: false.
      poolPingEnabled :侦测查询的开关。如果打开,你必须为 poolPingQuery 属性设置一个有效的 SQL 语句(最好是速度很快的一个)。默认是 false。

    • poolPingConnectionsNotUsedFor – This configures how often the poolPingQuery will be used. This can be set to match the typical timeout for a database connection, to avoid unnecessary pings. Default: 0 (i.e. all connections are pinged every time – but only if poolPingEnabled is true of course).
      poolPingConnectionsNotUsedFor :设置 poolPingQuery 被使用的频率。它可以被设置为和数据库连接超时时间一样以避免不必要的 ping。默认是0(即在 poolPingEnabled 打开时,所有连接每一时刻都会 ping)。

    2.3.1.3 JNDI

    This implementation of DataSource is intended for use with containers such as EJB or Application Servers that may configure the DataSource centrally or externally and place a reference to it in a JNDI context.
    作用:这种 DataSource 的实现是为了在像 EJB 或应用服务器这类的容器中使用,容器可以集中或者在外部配置 DataSource,并设置一个 JNDI 上下文的引用。

    This DataSource configuration only requires two properties:
    这种 DataSource 的配置只需要两个属性:

    • initial_context – This property is used for the Context lookup from the InitialContext (i.e. initialContext.lookup(initial_context)). This property is optional, and if omitted, then the data_source property will be looked up against the InitialContext directly.
      initial_context :这个属性被用来从 InitialContext 中寻找上下文(即 initialContext.lookup(initial_context))。该属性是可选的,如果忽略该属性,data_source 元素就会直接从 InitialContext 中寻找。

    • data_source – This is the context path where the reference to the instance of the DataSource can be found. It will be looked up against the context returned by the initial_context lookup, or against the InitialContext directly if no initial_context is supplied.
      data_source :可以找到的 DataSource 实例的引用位置的上下文路径。它将会在 initial_context 查找返回的上下文中查找,或者在未设置 initial_context 时直接在 InitialContext 中查找。

    Similar to the other DataSource configurations, it’s possible to send properties directly to the InitialContext by prefixing those properties with env., for example:env.encoding=UTF8.This would send the property encoding with the value of UTF8 to the constructor of the InitialContext upon instantiation.
    和其他 DataSource 的配置一样,它也可以通过添加前缀 env. 直接传递属性到 InitialContext。如:env.encoding=UTF8。这样就可以在 InitialContext 实例化时,向其构造器传递值为 UTF8 的属性 encoding 属性。

    2.3.2 使用第三方 DataSource

    You can plug any 3rd party DataSource by implementing the interface org.apache.ibatis.datasource.DataSourceFactory:
    你可以通过实现接口 org.apache.ibatis.datasource.DataSourceFactory 来使用任意的第三方数据源:

    public interface DataSourceFactory {
      void setProperties(Properties props);
      DataSource getDataSource();
    }
    

    org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory can be used as super class to build new datasource adapters. For example this is the code needed to plug C3P0:
    org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory 可以被用作父类来构建新的数据源适配器。例如这是插入 C3P0 数据源所必须的代码:

    import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
    import com.mchange.v2.c3p0.ComboPooledDataSource;
            
    public class C3P0DataSourceFactory extends UnpooledDataSourceFactory {
      public C3P0DataSourceFactory() {
        this.dataSource = new ComboPooledDataSource();
      }
    }
    

    To set it up, add a property for each setter method you want MyBatis to call. Follows below a sample configuration which connects to a PostgreSQL database:
    为了使其工作,需要为每个想要 MyBatis 调用的 setter 方法在配置文件中增加对应的属性。下面是可以连接 PostgreSQL 数据库的配置的例子:

    <dataSource type="org.myproject.C3P0DataSourceFactory">  
      <property name="driver" value="org.postgresql.Driver"/>  
      <property name="url" value="jdbc:postgresql:mydb"/>  
      <property name="username" value="postgres"/>  
      <property name="password" value="root"/>
    </dataSource>
    

    最后

    说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!

    当前版本:mybatis-3.5.0
    官网文档:MyBatis
    官网翻译:MyBatis 简体中文
    项目实践:MyBatis Learn

    相关文章

      网友评论

          本文标题:Mybatis 文档篇 2.7:Configuration 之

          本文链接:https://www.haomeiwen.com/subject/fsznmqtx.html