Configuration file of MyBatis study notes

foreword

DEMO

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- mybatis 官网配置文档:https://mybatis.org/mybatis-3/zh/configuration.html -->
    <!-- 属性,可以直接赋值,也可以外部进行配置,同一属性名以最后加载的为准    通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的则是 properties 元素中指定的属性。-->    <properties resource="db-connection.properties">        <property name="driver" value="${driver}"/>        <property name="url" value="${url}"/>        <property name="username" value="${username}"/>        <property name="password" value="${password}"/>    </properties>
    <!-- settings 官网配置:https://mybatis.org/mybatis-3/zh/configuration.html#settings -->   <!-- <settings>        &lt;!&ndash; 这是是使用logback的配置&ndash;&gt;        &lt;!&ndash;<setting name="logPrefix" value="dao."/>&ndash;&gt;        &lt;!&ndash; 使用LOG4J打印日志&ndash;&gt;        &lt;!&ndash;<setting name="logImpl" value="LOG4J"/>&ndash;&gt;    </settings>-->
    <!-- 实体类别名设置 -->    <typeAliases>        <package name="com.fly9.domain"/>    </typeAliases>
    <!-- 类型处理器 https://mybatis.org/mybatis-3/zh/configuration.html#typeHandlers -->    <typeHandlers>            </typeHandlers>
    <!-- 插件(略) https://mybatis.org/mybatis-3/zh/configuration.html#plugins -->
    <!--配置环境,可以配置多个环境,但是每个 SqlSessionFactory 实例只能选择一种环境。-->    <environments default="development">        <environment id="development">            <!--事务管理的配置 -->            <transactionManager type="JDBC"></transactionManager>            <!--数据源的配置-->            <dataSource type="POOLED">                <property name="driver" value="${driver}"/>                <property name="url" value="${url}"/>                <property name="username" value="${username}"/>                <property name="password" value="${password}"/>                <!-- 事务隔离级别,默认数据库事务隔离级别-->                <!--<property name="defaultTransactionIsolationLevel" value=""/>-->            </dataSource>        </environment>    </environments>
    <!--映射器(mappers)-->    <mappers>        <package name="com.fly9.mapper"/>    </mappers></configuration>

properties attribute configuration

Mybatis official property document: https://mybatis.org/mybatis-3/zh/configuration.html#properties property, which can be directly assigned or configured externally. The same property name is subject to the last loaded one; passed through method parameters The properties specified in the resource/url attribute have the highest priority, followed by the configuration file specified in the resource/url attribute, and the lowest priority is the property specified in the properties element.

driver=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://192.168.5.129:3306/db_learnusername=rootpassword=123456

<properties resource="db-connection.properties">    <property name="driver" value="${driver}"/>    <property name="url" value="${url}"/>    <property name="username" value="${username}"/>    <property name="password" value="${password}"/></properties>

settings configuration

Mybatis official configuration document: https://mybatis.org/mybatis-3/zh/configuration.html#settings

<settings>  <!--这是是使用logback的配置,需要在 logback 中配置 <logger name="dao" level="DEBUG"/> -->  <setting name="logPrefix" value="dao."/>  <!-- 使用LOG4J打印日志 -->  <setting name="logImpl" value="LOG4J"/></settings>

  • NONE: do not do anything

  • WARNING: output warning log (the log level of 'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' must be set to WARN)

  • FAILING: Mapping failed (throws SqlSessionException) | NONE, WARNING, FAILING | NONE || defaultExecutorType | Configure the default executor. SIMPLE is an ordinary executor; REUSE executor will reuse prepared statements (PreparedStatement); BATCH executor not only reuses statements but also performs batch updates. | SIMPLE REUSE BATCH | SIMPLE || defaultStatementTimeout | Set the timeout, which determines the number of seconds the database driver waits for the database response. | Any positive integer | Not set (null) || defaultFetchSize | Sets a suggested value for the driver's result set fetch size (fetchSize). This parameter can only be overridden in query settings. | Any positive integer | Not set (null) || defaultResultSetType | Specifies the default scrolling strategy for statements. (Added in 3.5. 2) | FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT (equivalent to unset) | unset (null) || safeRowBoundsEnabled | Whether to allow pagination (RowBounds) in nested statements. Set to false if allowed. | true | false | False || safeResultHandlerEnabled | Whether to allow the use of result handlers (ResultHandler) in nested statements. Set to false if allowed. | true | false | True || mapUnderscoreToCamelCase | Whether to enable the automatic mapping of camel case, that is, to map from the classic database column name A_COLUMN to the classic Java property name aColumn. | true | false | False || localCacheScope | MyBatis uses the local cache mechanism (Local Cache) to prevent circular references and speed up repeated nested queries. The default value is SESSION, which will cache all queries executed in a session. If the setting value is STATEMENT, the local cache will only be used to execute statements, and different queries for the same SqlSession will not be cached. | SESSION | STATEMENT | SESSION || jdbcTypeForNull | The default JDBC type for null values ​​when no specific JDBC type is specified for the parameter. Some database drivers need to specify the JDBC type of the column. In most cases, just use the general type, such as NULL, VARCHAR or OTHER. | JdbcType constant, common values: NULL, VARCHAR, or OTHER. | OTHER || lazyLoadTriggerMethods | Specifies which methods of the object trigger a lazy load. | A comma-separated list of methods. | equals, clone, hashCode, toString || defaultScriptingLanguage | Specifies the default scripting language to use for dynamic SQL generation. | A type alias or fully qualified class name. | org.apache.ibatis.scripting.xmltags.XMLLanguageDriver || defaultEnumTypeHandler | Specifies the default TypeHandler used by Enum. (Added in 3.4.5) | A type alias or fully qualified class name. | org.apache.ibatis.type.EnumTypeHandler || callSettersOnNulls | Specifies whether to call the setter (put) method of the map object when the value in the result set is null, which depends on Map.keySet() or null value Useful for initialization. Note that primitive types (int, boolean, etc.) cannot be set to null. | true | false | false || returnInstanceForEmptyRow | MyBatis returns null by default when all columns of the returned row are empty. When this setting is turned on, MyBatis will return an empty instance. Note that it also works with nested result sets (such as collections or associations). (Added in 3.4.2) | true | false | false || logPrefix | Specifies the prefix that MyBatis adds to log names. | any string | not set || logImpl | Specifies the concrete implementation of the log used by MyBatis, if not specified, it will be found automatically. | SLF4J | LOG4J (deprecated since 3.5. 9) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | Not set || proxyFactory | Specifies the proxy tool used by Mybatis to create lazy-loadable objects. | CGLIB | JAVASSIST | JAVASSIST (MyBatis 3.3 and above) || vfsImpl | Specifies the implementation of VFS | Fully qualified class names of custom VFS implementations, separated by commas. | not set || useActualParamName | Allows using names in method signatures as statement parameter names. In order to use this feature, your project must be compiled with Java 8 with the -parameters option. (Added in 3.4.1) | true | false | true || configurationFactory | Specifies a class that provides Configuration instances. The returned Configuration instance is used to load the lazy loaded property values ​​of the deserialized object. This class must contain a method with the signature static Configuration getConfiguration(). (Added in 3.2.3) | A type alias or fully qualified class name. | Not set || shrinkWhitespacesInSql | Remove redundant whitespace characters from SQL. Note that this also affects literal strings in SQL. (Added in 3.5.5) | true | false | false || defaultSqlProviderType | Specifies an sql provider class that holds provider method (Since 3.5.6). This class apply to the type(or value) attribute on sql provider annotation( eg @SelectProvider),

typeAliases alias configuration

Mybatis official configuration document: https://mybatis.org/mybatis-3/zh/configuration.html#typeAliases

<!-- 实体类别名设置 --><typeAliases>    <package name="com.fly9.domain"/></typeAliases>

typeHandlers type handler configuration

Mybatis official configuration document: https://mybatis.org/mybatis-3/zh/configuration.html#typeHandlers

<typeHandlers>
</typeHandlers>

plugins configuration

Mybatis official configuration document: https://mybatis.org/mybatis-3/zh/configuration.html#plugins

environments environment configuration

Mybatis official configuration document: https://mybatis.org/mybatis-3/zh/configuration.html#environments

<!--配置环境,可以配置多个环境,但是每个 SqlSessionFactory 实例只能选择一种环境。--><environments default="development">    <environment id="development">        <!-- 事务管理的配置 -->        <transactionManager type="JDBC"></transactionManager>        <!-- 数据源的配置 -->        <dataSource type="POOLED">            <property name="driver" value="${driver}"/>            <property name="url" value="${url}"/>            <property name="username" value="${username}"/>            <property name="password" value="${password}"/>            <!-- 事务隔离级别,默认数据库事务隔离级别-->            <!--<property name="defaultTransactionIsolationLevel" value=""/>-->        </dataSource>    </environment></environments>

Data Source (dataSource) The dataSource element uses the standard JDBC data source interface to configure the resources of the JDBC connection object.

  • Most MyBatis applications will configure datasources as in the examples. Although data source configuration is optional, it is necessary to configure the data source if lazy loading is to be enabled.

There are three built-in data source types (ie type="[UNPOOLED|POOLED|JNDI]"): UNPOOLED - This data source implementation will open and close the connection on each request. Although a little slow, it is a good choice for simple applications that do not require high availability of database connections. Performance depends on the database used, for some databases, it is not important to use a connection pool, this configuration is very suitable for this situation. The data source of UNPOOLED type only needs to configure the following five properties:

  • driver - This is the fully qualified Java class name of the JDBC driver (not the data source class that may be included in the JDBC driver).

  • url – This is the JDBC URL address of the database.

  • username – username to log in to the database.

  • password – the password to log in to the database.

  • defaultTransactionIsolationLevel – The default connection transaction isolation level.

  • defaultNetworkTimeout – The default network timeout (in milliseconds) to wait for database operations to complete. See the API documentation for java.sql.Connection#setNetworkTimeout() for more information.

Optionally, you can also pass properties to the database driver. Just prefix the property name with "driver.", for example:

  • driver.encoding=UTF8

This will pass the encoding property as UTF8 to the database driver via the DriverManager.getConnection(url, driverProperties) method. POOLED - This data source implementation utilizes the concept of "pools" to organize JDBC connection objects, avoiding the initialization and authentication time necessary to create new connection instances. This approach is popular and enables concurrent web applications to respond quickly to requests. In addition to the properties under UNPOOLED mentioned above, there are more properties used to configure the data source of POOLED:

  • poolMaximumActiveConnections – the number of active (in use) connections that can exist at any one time, default: 10

  • poolMaximumIdleConnections – The number of idle connections that may exist at any one time.

  • poolMaximumCheckoutTime – before being forced to return, the connection in the pool is checked out (checked out) time, default value: 20000 milliseconds (ie 20 seconds)

  • poolTimeToWait – This is a low-level setting. If it takes a long time to obtain a connection, the connection pool will print the status log and try to obtain a connection again (to avoid failing and not printing the log in case of misconfiguration). Default value: 20000 milliseconds (ie 20 seconds).

  • poolMaximumLocalBadConnectionTolerance – This is a low-level setting about the tolerance of bad connections, which is applied to each thread that tries to get a connection from the buffer 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 retries should not exceed the sum of poolMaximumIdleConnections and poolMaximumLocalBadConnectionTolerance. Default: 3 (added in 3.4.5)

  • poolPingQuery – A detection query sent to the database to verify that the connection is working and ready to accept requests. The default is "NO PING QUERY SET", which causes most database drivers to return appropriate error messages when errors occur.

  • poolPingEnabled – whether to enable detection query. If enabled, you need to set the poolPingQuery attribute to an executable SQL statement (preferably a very fast SQL statement), default value: false.

  • poolPingConnectionsNotUsedFor – configures the frequency of poolPingQuery. Can be set to be the same as the database connection timeout to avoid unnecessary probes, default value: 0 (that is, all connections are probed every time - of course only applies when poolPingEnabled is true).

JNDI - This data source implementation is intended for use in containers such as EJBs or application servers, which can configure data sources centrally or externally, and place a reference to the data source in a JNDI context. This datasource configuration requires only two properties:

  • initial_context – This property is used to look up the context in the InitialContext (ie, initialContext.lookup(initial_context)). This is an optional attribute, if omitted, the data_source attribute will be looked for directly from the InitialContext.

  • data_source – This is the context path that refers to the location of the data source instance. When the initial_context configuration is provided, it will be searched in the returned context, and if not provided, it will be searched directly in the InitialContext.

Similar to other data source configurations, properties can be passed directly to the InitialContext by adding the prefix "env." for example:

  • env.encoding=UTF8

This will pass an encoding attribute with a value of UTF8 to the constructor of the InitialContext when it is instantiated.

mappers mapper configuration

Mybatis official configuration document: https://mybatis.org/mybatis-3/zh/configuration.html#mappers

<!-- 映射器(mappers)--><mappers>    <package name="com.fly9.mapper"/></mappers>

Guess you like

Origin blog.csdn.net/m0_69804655/article/details/130265681