Spring integrates MyBatis configuration
1.pom.xml dependency
- Add the dependent package of mybatis
<!-- mybatis Frame package start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency> <!-- mybatis Frame package end --> <!-- Database driven --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <!--Ali druid Connection pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency>
2.mybatis-config.xml
- The configuration of setting tag is to configure some behaviors of MyBatis framework runtime, such as caching, delayed loading, result set control, actuator, paging settings, naming rules and a series of control parameters. All setting configurations are placed in the parent tag settings tag.
- These are extremely important tuning settings in MyBatis, which change the runtime behavior of MyBatis. The following table describes the meaning and default values of each setting in the setting.
Set name | describe | Effective value | Default value |
---|---|---|---|
cacheEnabled | Globally turn on or off any cache configured in all mapper profiles. | true | false | true |
lazyLoadingEnabled | Global switch for delayed loading. When turned on, all associated objects are loaded late. In a specific association relationship, the switch state of the item can be overridden by setting the fetchType property. | true | false | false |
aggressiveLazyLoading | When on, the call of any method will load all the deferred load properties of the object. Otherwise, each deferred load attribute will be loaded on demand (refer to lazyLoadTriggerMethods). | true | false | false (true by default in versions 3.4.1 and earlier) |
multipleResultSetsEnabled | Whether to allow a single statement to return multiple result sets (database driver support is required). | true | false | true |
useColumnLabel | Use column labels instead of column names. The actual performance depends on the database driver. For details, please refer to the relevant documents of the database driver or observe through comparative test. | true | false | true |
useGeneratedKeys | Allow JDBC to support automatic generation of primary keys, which requires database driver support. If set to true, the auto generated primary key is enforced. Although some database drivers do not support this feature, it still works (such as Derby). | true | false | False |
autoMappingBehavior | Specify how MyBatis should automatically map columns to fields or attributes. NONE means to turn off automatic mapping; PARTIAL automatically maps only fields that do not have nested result mappings defined. FULL automatically maps any complex result set (whether nested or not). | NONE, PARTIAL, FULL | PARTIAL |
autoMappingUnknownColumnBehavior | Specifies the behavior of discovering unknown columns (or unknown attribute types) that are automatically mapped to. NONE: do nothing WARNING: output WARNING log ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior 'log level must be set to WARN) FAILING: mapping failed (sqlsessionexception thrown) | NONE, WARNING, FAILING | NONE |
defaultExecutorType | Configure the default actuator. SIMPLE is an ordinary actuator; The REUSE executor will REUSE the prepared statement; BATCH executors not only REUSE statements, but also perform BATCH updates. | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | Set the timeout, which determines the number of seconds the database driver waits for a database response. | Any positive integer | Not set (null) |
defaultFetchSize | Set a recommended value for the fetchSize of the driven result set. This parameter can only be overridden in query settings. | Any positive integer | Not set (null) |
defaultResultSetType | Specifies the default scrolling policy for the statement. (added to 3.5.2) | FORWARD_ ONLY | SCROLL_ SENSITIVE | SCROLL_ Default | not set (equivalent to default) | Not set (null) |
safeRowBoundsEnabled | Whether paging (rowboundaries) is allowed in nested statements. Set to false if allowed. | true | false | False |
safeResultHandlerEnabled | Whether to allow the use of result handler in nested statements. Set to false if allowed. | true | false | True |
mapUnderscoreToCamelCase | Whether to enable automatic hump naming mapping, that is, from the classic database column name A_COLUMN maps to the classic Java property name aColumn. | true | false | False |
localCacheScope | MyBatis uses the Local Cache mechanism to prevent circular references and accelerate repeated nested queries. The default value is SESSION, which caches all queries executed in a SESSION. If the value is set to state, the Local Cache will only be used to execute statements, and different queries of the same SqlSession will not be cached. | SESSION | STATEMENT | SESSION |
jdbcTypeForNull | When no specific JDBC type is specified for the parameter, the default JDBC type of NULL value. Some database drivers need to specify the JDBC type of columns. In most cases, they can directly 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 deferred load. | Comma separated list of methods. | equals,clone,hashCode,toString |
defaultScriptingLanguage | Specifies the default scripting language used 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 to 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 mapping object when the value in the result set is null, which depends on the map Keyset() or null value is useful for initialization. Note that basic types (int, boolean, etc.) cannot be set to null. | true | false | false |
returnInstanceForEmptyRow | When all columns of the returned row are empty, MyBatis returns null by default. When this setting is enabled, MyBatis will return an empty instance. Note that it also applies to nested result sets, such as collections or associations. (added to 3.4.2) | true | false | false |
logPrefix | Specifies the prefix that MyBatis adds to the log name. | Any string | Not set |
logImpl | Specify the specific implementation of the log used by MyBatis. If it is not specified, it will be found automatically. | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | Not set |
proxyFactory | Specifies the proxy tool used by Mybatis to create deferred loading objects. | CGLIB | JAVASSIST | JAVASSIST (MyBatis 3.3 above) |
vfsImpl | Specify the implementation of VFS | The fully qualified names of the classes implemented by the custom VFS are separated by commas. | Not set |
useActualParamName | It is allowed to use the name in the method signature as the statement parameter name. In order to use this feature, your project must be compiled in Java 8 with the - parameters option. (added to 3.4.1) | true | false | true |
configurationFactory | Specify a class that provides an instance of Configuration. The returned Configuration instance is used to load the deferred load property value of the deserialized object. This class must contain a method with the signature static Configuration getConfiguration(). (added to 3.2.3) | A type alias or fully qualified class name. | Not set |
shrinkWhitespacesInSql | Remove extra space characters from SQL. Note that this also affects text strings in SQL. (added to 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(e.g. @SelectProvider), when these attribute was omitted. | A type alias or fully qualified class name | Not set |
Full configuration:
<settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="false"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="25"/> <setting name="defaultFetchSize" value="100"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="mapUnderscoreToCamelCase" value="false"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="OTHER"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> </settings>
Configuration I use:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="false"></setting> <setting name="useGeneratedKeys" value="true"></setting> <setting name="defaultExecutorType" value="REUSE"></setting> <setting name="logImpl" value="STDOUT_LOGGING"></setting> </settings> </configuration>
3.dbconfig.properties
- Database connection configuration item of mybatis
url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false driverClassName=com.mysql.cj.jdbc.Driver password=123456 username=root maxActive=20 initialSize=1 maxWait=60000 maxIdle=15 minIdle=10 timeBetweenEvictionRunsMillis=60000 minEvictableIdleTimeMillis=300000 validationQuery=SELECT 'x' testWhileIdle=true testOnBorrow=false testOnReturn=false removeAbandoned=true maxOpenPreparedStatements=20 removeAbandonedTimeout=1800 logAbandoned=true
4.spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 1.Configure Ali druid Connection pool --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <!-- Basic information of configuration database --> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="driverClassName" value="${driverClassName}"/> <property name="maxActive" value="${maxActive}"/> <property name="initialSize" value="${initialSize}"/> </bean> <!-- 2.to configure spring Data source for --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name="dataSource" ref="dataSource"/> </bean> <!-- 3.to configure mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 3.1 to configure mybatis config --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 3.2 Configure scan mybatis Map file path --> <property name="mapperLocations" value="classpath:mybatis/*/*.xml"/> </bean> <!-- 4.be similar to jdbcTemplate Help class --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"></constructor-arg> </bean> </beans>