Mybatis related configuration

Set the Configuration information

Configuration configuration = new Configuration(); // Create a JDBC Transaction manager using JdbcTransactionFactory // Create a DataSource Environment Environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource("org.***.jdbcDriver", "jdbc:***", "user", "123456")); / / 2. Set up the environment information configuration. SetEnvironment (environment); / / 3. Settings are the increase configuration. SetUseGeneratedKeys (true); configuration.addMapper(Mapper.class);Copy the code
  1. Set the Environment variable Environment, which can also be configured using XML

     <environments default="development">
       <environment id="development">
       </environment>
     </environments>
    Copy the code
    • The environment ID used by default (for example: default=”development”).
    • The environment ID defined by each environment element (for example: ID =”development”).

    MyBatis can be configured for a variety of environments, in short, you can apply SQL mapping to a variety of databases. For example, development, test, and production environments require different configurations; Or you want to use the same SQL mapping across multiple production databases with the same Schema.

  2. Set up the transaction manager via TransactionFactory, or XML methods, as shown below

<environments default="development"> <environment id="development"> <transactionManager type="JDBC"> <property name="..." value="..." /> </transactionManager> </environment> </environments>Copy the code

MyBatis: JDBC and MANAGED (type=”JDBC/MANAGED”)

  • JDBC – Directly uses the JDBC commit and rollback functionality, which relies on connections obtained from data sources to manage transaction scopes. * * * *

  • MANAGED – Lets the container manage the entire life cycle of a transaction. Never commit or roll back a connection, it closes the connection by default. If some containers do not want the connection to be closed, set the closeConnection property to false to prevent the default closing behavior. Such as:

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

Neither of these transaction manager types requires any properties to be set. Use TransactionFactory interface implementation instead of such as JdbcTransactionFactory and ManagedTransactionFactory.

Public interface TransactionFactory {default void setProperties(Properties props) {// Starting from 3.5.2, This method is the default // empty implementation} Transaction newTransaction(Connection conn); Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit); }Copy the code

After the transaction manager is instantiated, the properties configured in the XML are passed to the setProperties() method. JdbcTransaction: ManagedTransaction: JdbcTransaction: ManagedTransaction: JdbcTransaction: ManagedTransaction: JdbcTransaction: ManagedTransaction: JdbcTransaction: ManagedTransaction

 public interface Transaction {
   Connection getConnection() throws SQLException;
   void commit() throws SQLException;
   void rollback() throws SQLException;
   void close() throws SQLException;
   Integer getTimeout() throws SQLException;
 }
Copy the code
JdbcTransaction ManagedTransaction
Property access: protected Property access permission: private
public void commit() throws SQLException { if (connection ! = null && ! connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug(“Committing JDBC Connection [” + connection + “]”); } connection.commit(); }} public void commit() throws SQLException { // Does nothing }
public void rollback() throws SQLException { if (connection ! = null && ! connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug(“Rolling back JDBC Connection [” + connection + “] “); } connection.rollback(); }} public void rollback() throws SQLException { // Does nothing }
protected void openConnection() throws SQLException { if (log.isDebugEnabled()) { log.debug(“Opening JDBC Connection”); } connection = dataSource.getConnection(); if (level ! = null) { connection.setTransactionIsolation(level.getLevel()); }setDesiredAutoCommit(autoCommit);// Set auto commit} protected void openConnection() throws SQLException { if (log.isDebugEnabled()) { log.debug(“Opening JDBC Connection”); } this.connection = this.dataSource.getConnection(); if (this.level != null) { this.connection.setTransactionIsolation(this.level.getLevel()); } }
public void close() throws SQLException { if (connection ! = null) {resetAutoCommit();if (log.isDebugEnabled()) { log.debug(“Closing JDBC Connection [” + connection + “]”); } connection.close(); }} public void close() throws SQLException { if (this.closeConnection && this.connection != null) { if (log.isDebugEnabled()) { log.debug(“Closing JDBC Connection [” + this.connection + “]”); } this.connection.close(); } }
  1. DataSource, Mybatis3 there are three types of dataSource: UNPOOLED/POOLED/JNDI

    UNPOOLED – Connections are opened and closed on each request. For programs that do not require high availability of database connections. The UNPOOLED data source needs to be configured as follows:

    • driver– This is the fully qualified Java class name of the JDBC driver (not the data source class that might be included in the JDBC driver).
    • url– This is the JDBC URL of the database.
    • username– User name for logging in to the database.
    • password– Password for logging in to the database.
    • defaultTransactionIsolationLevel– Default connection transaction isolation level.
    • defaultNetworkTimeout– Default network timeout duration (in milliseconds) to wait for database operations to complete.

    POOLED – Supports pooling of database connections, avoiding the initialization and authentication time required when creating new connection instances. Configure POOLED data source properties:

    • poolMaximumActiveConnections– Maximum number of connections. Default value: 10
    • poolMaximumIdleConnections– Number of idle connections that may exist at any time. (Note: Any time, default 5)
    • poolMaximumCheckoutTime— Time for connections in the pool to be checked out before being forced back. Default: 20000 ms (20 s)
    • poolTimeToWait– The connection pool prints a status log and tries to obtain a connection again (to avoid continuous failure and no log in case of misconfiguration). Default value: 20000 ms (20 seconds).
    • poolMaximumLocalBadConnectionTolerance— This is a low-level setting on bad connection tolerance that applies to every thread that tries to fetch a connection from the cache pool. If the thread gets a bad connection, the data source allows the thread to try to get a new connection, but the number of attempts should not exceed thatpoolMaximumIdleConnectionspoolMaximumLocalBadConnectionToleranceThe sum. Default value: 3
    • poolPingQuery– Detection queries sent to the database to verify that the connection is working properly and ready to accept requests. The default is “NO PING QUERY SET”, ensuring that most database drivers return appropriate error messages when they fail.
    • poolPingEnabled– Whether to enable detection query. If yes, you need to set this parameterpoolPingQueryAttribute to an executable SQL statement (preferably a very fast SQL statement). Default: false.
    • poolPingConnectionsNotUsedFor– poolPingQuery frequency. Can be set to the same as the database connection timeout to avoid unnecessary detection, default: 0 (that is, all connections are detected at any time – only if poolPingEnabled is true).

    JNDI – Used in a container such as an EJB or application server, the container can centrally or externally configure the data source and then reference it in the JNDI context. The configuration requires only two properties:

    • initial_context– Used to find the context in InitialContext (that is, initialContext.lookup(Initial_context)). Is an optional attribute, if omitted, the datA_source attribute will be looked for directly from the InitialContext.
    • data_source– The context path that references the location of the data source instance. The initial_Context configuration is looked up in its returned context when provided, or directly in the InitialContext when not provided.

    You can pass attributes directly to InitialContext by prefixing it with “env.” Such as:

    • env.encoding=UTF8InitialContext is instantiated by passing a value to its constructorUTF8encodingattribute

    The DataSourceFactory is typically implemented using third-party data sources:

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

    Org. Apache. Ibatis. The datasource. Unpooled. UnpooledDataSourceFactory can be used as the parent class to build a new data source adapter, such as the insert C3P0 data required for the code below:

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

    To make this work, remember to add a property to the configuration file for each setter method you want MyBatis to call. Here is an example of how to connect to a PostgreSQL database:

     <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>
    Copy the code

The resources

Mybatis 中文 API:Mybatis.org/mybatis-3/z….

JDBC:Juejin. Cn/post / 700629…