MyBatis environments

In MyBatis, the main function of the operating environment is to configure database information. It can configure multiple databases. Generally speaking, only one of them needs to be configured.

Below it is divided into two configurable elements: transaction manager (transactionManager), data source (dataSource).

In actual work, in most cases,  Spring will be used  to manage the transactions of data sources and databases, which will be explained later in our tutorial. In this section we will explore the classes implemented by MyBatis itself.

Run environment configuration, the code is as follows.

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC" />
        <dataSource type="POOLED">
            <property name="driver" value="${database.driver}" />
            <property name="url"
                value="${database.url}" />
            <property name="username" value="${database.username}" />
            <property name="password" value="${database.password}" />
        </dataSource>
    </environment>
</environments>

Two elements are used here: transactionManager and environment.

transactionManager (transaction manager)

In MyBatis, transactionManager provides two implementation classes, it needs to implement the interface Transaction (org.apache.ibatis.transaction.Transaction), and its definition code is shown below.

public interface Transaction {
    Connection getConnection() throws SQLException;

    void commit() throws SQLException;

    void rollback() throws SQLException;

    void close() throws SQLException;

    Integer getTimeout() throws SQLException;
}

It can be seen from the method that its main work is to commit, rollback and close the transaction of the database. MyBatis provides two implementation classes for Transaction: JdbcTransaction and ManagedTransaction, as shown in Figure 1.

Implementation class of Transaction


Figure 1 Implementation class of Transaction


So it corresponds to two factories: JdbcTransactionFactory and ManagedTransactionFactory, this factory needs to implement the TransactionFactory interface, through which the corresponding Transaction objects will be generated. So the transaction manager can be configured in the following two ways:

<transactionManager type="JDBC"/>
<transactionManager type="MANAGED"/>

Here is a brief explanation.

JDBC is implemented using JdbcTransaction objects generated by JdbcTransactionFactory. It operates on the commit and rollback of the database in the way of JDBC.

MANAGED is implemented using ManagedTransaction objects generated by ManagedTransactionFactory. Its commit and rollback methods do not perform any operations, but hand over the transaction to the container. By default, it will close the connection, but some containers do not want this, so you need to set the closeConnection property to false to prevent it from closing by default.

When we don't want to adopt the rules of MyBatis, we can configure it like this:

<transactionManager type="com.mybatis.transaction.MyTransactionFactory"/>

Implement a custom transaction factory, the code is as follows.

public class MyTransactionFactory implements TransactionFactory {
    @Override
    public void setProperties(Properties props) {
    }
    @Override
    public Transaction newTransaction(Connection conn) {
        return new MyTransaction(conn);
    }
    @Override
    public Transaction newTransaction(DataSource dataSource, TransactionlsolationLevel level, boolean autoCommit) {
        return new MyTransaction(dataSource, level, autoCommit);
    }
}

Here, the factory method defined by TransactionFactory is implemented. At this time, the transaction implementation class MyTransaction is needed, which is used to implement the Transaction interface. The code is as follows.

public class MyTransaction extends JdbcTransaction implements Transaction {

    public MyTransaction(DataSource ds, TransactionIsolationLevel desiredLevel,
            boolean desiredAutoCommit) {
        super(ds, desiredLevel, desiredAutoCommit);
    }

    public MyTransaction(Connection connection) {
        super(connection);
    }

    public Connection getConnection() throws SQLException {
        return super.getConnection();
    }

    public void commit() throws SQLException {
        super.commit();
    }

    public void rollback() throws SQLException {
        super.rollback();
    }

    public void close() throws SQLException {
        super.close();
    }

    public Integer getTimeout() throws SQLException {
        return super.getTimeout();
    }
}

In this way, special needs can be met by customizing transaction rules.

environment data source environment

The main function of environment is to configure the database. In MyBatis, the database is provided by three factory classes: PooledDataSourceFactory, UnpooledDataSourceFactory and JndiDataSourceFactory. The first two correspond to generate PooledDataSource and UnpooledDataSource class objects, while JndiDataSourceFactory will get the external container according to the JNDI information The implemented database connection object.

Regardless of these three factory classes, the final product will be a database connection object that implements the DataSource interface.

Since there are three data sources, they can be configured in the following form.

<dataSource type="UNPOOLED">
<dataSource type="POOLED">
<dataSource type="JNDI">

Discuss these three data sources and their properties.

1. UNPOOLED

UNPOOLED uses a non-database pool management method, and each request will open a new database connection, so the creation will be slower. It can be used in occasions that do not have high performance requirements.

For some databases, it is not important to use a connection pool, so it is also an ideal choice. The data source of UNPOOLED type can be configured with the following properties:

  • driver The name of the database driver, such as  com.mysql.jdbc.Driver of MySQL  .
  • url URL to connect to the database.
  • username username.
  • password Password.
  • defaultTransactionIsolationLevel The default connection transaction isolation level, about the isolation level, will be discussed later in the tutorial.


Passing properties to the database driver is also an option, note that the prefix of the property is "driver.", for example driver.encoding=UTF8. It will pass the encoding property of UTF8 to the database driver through the DriverManager.getConnection(url, driverProperties) method.

2. PARTIES

The data source POOLED uses the concept of "pool" to organize JDBC Connection objects. It will have some vacancy at the beginning, and the database connection has already been connected, so when requesting, there is no need to establish and verify, and it is unnecessary to create a new connection instance. initialization and authentication time necessary for It also controls the maximum number of connections to avoid system bottlenecks caused by too many connections.

In addition to the properties under UNPOOLED, there will be more properties to configure the data source of POOLED, as shown in Table 1:

Table 1 Description of data source properties for configuring POOLED
name illustrate
poolMaximumActiveConnections  is the number of active (that is, in use) connections that exist at any one time, with a default value of 10
poolMaximumIdleConnections is the number of idle connections that may exist at any time
halfMaximumCheckoutTime The time for a connection in the pool to be checked out before being forced to return. The default value is 20 000 milliseconds (ie 20 seconds)
poolTimeToWait Is a low-level setting. If it takes a long time to obtain a connection, it will print a status log to the connection pool and try to obtain a connection again (to avoid failures in the case of misconfiguration). The default value is 20 000 milliseconds (ie 20 Second).
poolPingQuery A probe query sent to the database to verify that the connection is in working order and ready to accept requests. The default is "NO PING QUERY SET", which causes most database drivers to fail with an appropriate error message.
poolPingEnabled Indicates whether detection queries are enabled. If enabled, the poolPingQuery attribute must also be set with an executable SQL statement (preferably a very fast SQL), the default value is false.
poolPingConnectionsNotUsedFor To configure the usage frequency of poolPingQuery. This can be set to match a specific database connection timeout to avoid unnecessary probes, the default is 0 (ie all connections are probed every time - only applies if poolPingEnabled is true).

3. JNDI

Datasources JNDI is implemented for use in containers such as EJBs or application servers, which can centrally or externally configure datasources and then place a reference to a JNDI context. This datasource configuration requires only two properties:

1)initial_context

Used to look up the context in InitialContext (ie, initialContext.lookup(initial_context)). initial_context is an optional attribute, if omitted, the data_source attribute will be looked up directly from InitialContext.

2)data_source

is the path that refers to the context of the location of the data source instance. When the initial_context configuration is provided, the data_source will be searched in the returned context; when the initial_context is not provided, the data_source will be directly searched in the InitialContext.

Similar to other data source configurations, it can directly pass properties to the initial context (InitialContext) by adding the prefix "env." For example, env.encoding=UTF8, when the initial context is instantiated, the encoding attribute value of UTF8 will be passed to its construction method.

MyBatis also supports third-party data sources, such as using DBCP data sources, then you need to provide a custom DataSourceFactory, the code is as follows.

public class DbcpDataSourceFactory implements DataSourceFactory {
    private Properties props = null;

    public void setProperties(Properties props) {
        this.props = props;
    }
    public DataSource getDataSource() {
        DataSource dataSource = null;
        dataSource = BasicDataSourceFactory.createDataSource(props);
        return dataSource;
    }
}

Then configure as follows:

<dataSource type="com.mybatis.dataSource.DbcpDataSourceFactory">
    <property name="driver" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="username" value="${database.username}" />
    <property name="password" value="${database.password}" />
</dataSource>

In this way, MyBatis will use the configured data source factory to generate the data source.

Guess you like

Origin blog.csdn.net/unbelievevc/article/details/132311235
Recommended