[MyBatis] Spring integrates MyBatis configuration

Posted by bishnu.bhatta on Fri, 11 Feb 2022 14:21:14 +0100

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>

Back to top

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 namedescribeEffective valueDefault value
cacheEnabledGlobally turn on or off any cache configured in all mapper profiles.true | falsetrue
lazyLoadingEnabledGlobal 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 | falsefalse
aggressiveLazyLoadingWhen 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 | falsefalse (true by default in versions 3.4.1 and earlier)
multipleResultSetsEnabledWhether to allow a single statement to return multiple result sets (database driver support is required).true | falsetrue
useColumnLabelUse 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 | falsetrue
useGeneratedKeysAllow 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 | falseFalse
autoMappingBehaviorSpecify 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, FULLPARTIAL
autoMappingUnknownColumnBehaviorSpecifies 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, FAILINGNONE
defaultExecutorTypeConfigure 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 BATCHSIMPLE
defaultStatementTimeoutSet the timeout, which determines the number of seconds the database driver waits for a database response.Any positive integerNot set (null)
defaultFetchSizeSet a recommended value for the fetchSize of the driven result set. This parameter can only be overridden in query settings.Any positive integerNot set (null)
defaultResultSetTypeSpecifies 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)
safeRowBoundsEnabledWhether paging (rowboundaries) is allowed in nested statements. Set to false if allowed.true | falseFalse
safeResultHandlerEnabledWhether to allow the use of result handler in nested statements. Set to false if allowed.true | falseTrue
mapUnderscoreToCamelCaseWhether 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 | falseFalse
localCacheScopeMyBatis 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 | STATEMENTSESSION
jdbcTypeForNullWhen 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
lazyLoadTriggerMethodsSpecifies which methods of the object trigger a deferred load.Comma separated list of methods.equals,clone,hashCode,toString
defaultScriptingLanguageSpecifies the default scripting language used for dynamic SQL generation.A type alias or fully qualified class name.org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandlerSpecifies the default TypeHandler used by Enum. (added to 3.4.5)A type alias or fully qualified class name.org.apache.ibatis.type.EnumTypeHandler
callSettersOnNullsSpecifies 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 | falsefalse
returnInstanceForEmptyRowWhen 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 | falsefalse
logPrefixSpecifies the prefix that MyBatis adds to the log name.Any stringNot set
logImplSpecify 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_LOGGINGNot set
proxyFactorySpecifies the proxy tool used by Mybatis to create deferred loading objects.CGLIB | JAVASSISTJAVASSIST (MyBatis 3.3 above)
vfsImplSpecify the implementation of VFSThe fully qualified names of the classes implemented by the custom VFS are separated by commas.Not set
useActualParamNameIt 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 | falsetrue
configurationFactorySpecify 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
shrinkWhitespacesInSqlRemove extra space characters from SQL. Note that this also affects text strings in SQL. (added to 3.5.5)true | falsefalse
defaultSqlProviderTypeSpecifies 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 nameNot 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>

Back to top

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

Back to top

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>

Back to top

Topics: Mybatis