Usage of properties and settings tags for Mybatis configuration

  • 2021-10-27 07:25:44
  • OfStack

Mybatis properties Tag and settings Tag

This time, we will describe the configuration of mybatis. The main configuration is based on the configuration file of mybatis. The configuration file is not complicated

Such as the following example:


<?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>
	<properties resource="jdbc.properties">
		<!-- <property name="database.driver" value="com.mysql.jdbc.Driver"/>
		 <property name="database.url" value="jdbc:mysql://localhost:3306/chapter4"/> 
			<property name="database.username" value="root"/> 
			<property name="database.password" value="123456"/> -->
	</properties>
	<typeAliases><!--  Alias  -->
		<!-- <typeAlias alias="role" type="com.learn.ssm.chapter4.pojo.Role"/> -->
		<package name="com.learn.ssm.chapter4.pojo" />
	</typeAliases>
	<typeHandlers>
		<!-- <typeHandler jdbcType="VARCHAR" javaType="string" handler="com.learn.ssm.chapter4.typehandler.MyTypeHandler" 
			/> -->
		<package name="com.learn.ssm.chapter4.typehandler" />
 
	</typeHandlers>
	<!--  Database environment  -->
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="com.learn.ssm.chapter4.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>
		</environment>
	</environments>
	
    <!-- 
	<databaseIdProvider type="DB_VENDOR">
		<property name="Oracle" value="oracle" />
		<property name="MySQL" value="mysql" />
		<property name="DB2" value="db2" />
	</databaseIdProvider>
	 -->
	<databaseIdProvider
		type="com.learn.ssm.chapter4.databaseidprovider.MyDatabaseIdProvider">
		<property name="msg" value=" Customize DatabaseIdProvider" />
	</databaseIdProvider>
	<mappers>
		<package name="com.learn.ssm.chapter4.mapper" />
	</mappers>
</configuration>

It should be noted that the configuration items of mybatis cannot be reversed from each other. If they are reversed, an exception will occur during the startup phase of mybatis, which will cause the program to fail.

The general order is as follows:


<?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>
	<properties></properties>
	<settings></settings>
	<typeAliases></typeAliases>
	<typeHandlers></typeHandlers>
	<objectFactory type=""></objectFactory>
	<plugins></plugins>
	<environments default="">
		<environment id="">
			<dataSource type=""></dataSource>
			<transactionManager type=""></transactionManager>
		</environment>
	</environments>
	<databaseIdProvider type=""></databaseIdProvider>
	<mappers></mappers>
</configuration>

1. properties attribute

properties attribute is used to configure some parameters for the system, which can be placed in xml file or properties file instead of java coding. This has the advantage of convenient management and modification without causing code recompilation. Generally speaking, there are the following three configuration methods:

properties child element:


<property name="database.driver" value="com.mysql.jdbc.Driver"/>
<property name="database.url" value="jdbc:mysql://localhost:3306/chapter4"/> 
<property name="database.username" value="root"/> 
<property name="database.password" value="123456"/>

As above, we need to identify the attribute name and attribute value inside the property tag. In this way, the name of the configured property and the corresponding property value are recorded in the xml file. At the same time can also use placeholder reference management, which is often seen in the writing of code, is a more popular mode of operation.


<property name="driver" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />

Such as the above attribute assignment method, the placeholder reference method is adopted, and the values written above are referenced by placeholder method. If we write this way, we need to define the sub-elements of properties under the properties tag above, which is similar to Example 1 shown.

Using the properties file:

This requires us to create an properties file:


database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/chapter4
database.username=root
database.password=123456

If we want to take advantage of the values defined in this file, we need to set the < properties > Tag's resource, whose value is the path of the package, is used as follows (assuming the file name is jdbc. properties):


<properties resource="jdbc.properties" />

In this way, multiple key values can be stored in one properties file, which is convenient for future modification and management. At the same time, it can also be passed in combination with the placeholders above.

Passing parameters using program passing:

In some cases, the number of user passwords in the database is confidential to developers and others. Operation and maintenance personnel need to encrypt the user name and password for confidentiality, and then configure them in properties files. At this time, they often need decryption to get to the real user name and password database, and it is impossible to use encrypted strings to link to the database. So assuming that there is already a tool for decryption, we need to decrypt the person and reset it to the properties file:


public class SqlSessionFactoryUtils { 
	private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class; 
	private static SqlSessionFactory sqlSessionFactory = null; 
	private SqlSessionFactoryUtils() {
	}
 
	public static SqlSessionFactory getSqlSessionFactory() {
		synchronized (LOCK) {
			if (sqlSessionFactory != null) {
				return sqlSessionFactory;
			}
			String resource = "mybatis-config.xml";
			InputStream inputStream;
			try {
				 inputStream = Resources.getResourceAsStream(resource);
				 sqlSessionFactory = new
				 SqlSessionFactoryBuilder().build(inputStream);
				
				 Passing encryption parameters by program , Change the user password to ciphertext before enabling it ..
				InputStream in = Resources.getResourceAsStream("jdbc.properties");
				Properties props = new Properties();
				props.load(in);
				String username = props.getProperty("database.username");
				String password = props.getProperty("database.password");
				//  Decrypt the user and password, and reset the 
				props.put("database.username", CodeUtils.decode(username));
				props.put("database.password", CodeUtils.decode(password));
				inputStream = Resources.getResourceAsStream(resource);
				//  Use program delivery to override the original properties Attribute parameter 
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, props);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			return sqlSessionFactory;
		}
	}
 
	public static SqlSession openSqlSession() {
		if (sqlSessionFactory == null) {
			getSqlSessionFactory();
		}
		return sqlSessionFactory.openSession();
	}
 
	public static void main(String[] args) {
		System.out.println(CodeUtils.encode("root"));
		System.out.println(CodeUtils.encode("123456"));
	}
 
	static class CodeUtils {
		private static String encode(String src) {
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(src.getBytes());
		}
 
		private static String decode(String des) {
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				return new String(decoder.decodeBuffer(des));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}

There is an example of passing parameters based on program passing. First, use Resource object to read an jdbc. properties file, then obtain the original configuration of user name and password, and decrypt, reset, finally use biuld method of SqlSessionFactoryBuilder class to transfer the parameters in properties to complete the coverage of the original ciphertext, and solve the security problem, and can safely connect to the database.

2. Settings label setting

This is the most complex configuration in mybatis, The settings in this tab can profoundly affect the underlying operation, but in most cases, it can be run by using the default configuration, without configuring this attribute. In most cases, it is enough to modify some commonly used rules, such as automatic mapping, hump naming mapping, cascading rules, whether to open cache, actuator type and so on.


<!-- settings是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 -->  
    <settings>  
        <!-- 该配置影响的所有映射器中配置的缓存的全局开关。默认值true -->  
      <setting name="cacheEnabled" value="true"/>  
      <!--延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。默认值false  -->  
      <setting name="lazyLoadingEnabled" value="true"/>  
        <!-- 是否允许单1语句返回多结果集(需要兼容驱动)。 默认值true -->  
      <setting name="multipleResultSetsEnabled" value="true"/>  
      <!-- 使用列标签代替列名。不同的驱动在这方面会有不同的表现, 具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。默认值true -->  
      <setting name="useColumnLabel" value="true"/>  
      <!-- 允许 JDBC 支持自动生成主键,需要驱动兼容。 如果设置为 true 则这个设置强制使用自动生成主键,尽管1些驱动不能兼容但仍可正常工作(比如 Derby)。 默认值false  -->  
      <setting name="useGeneratedKeys" value="false"/>  
     <!--  指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。 -->   
     <!-- 默认值PARTIAL -->  
      <setting name="autoMappingBehavior" value="PARTIAL"/>  
        
      <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>  
     <!--  配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。默认SIMPLE  -->  
      <setting name="defaultExecutorType" value="SIMPLE"/>  
      <!-- 设置超时时间,它决定驱动等待数据库响应的秒数。 -->  
      <setting name="defaultStatementTimeout" value="25"/>  
        
      <setting name="defaultFetchSize" value="100"/>  
      <!-- 允许在嵌套语句中使用分页(RowBounds)默认值False -->  
      <setting name="safeRowBoundsEnabled" value="false"/>  
      <!-- 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。  默认false -->  
      <setting name="mapUnderscoreToCamelCase" value="false"/>  
      <!-- MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。  
             默认值为 SESSION,这种情况下会缓存1个会话中执行的所有查询。  
            若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。  -->  
      <setting name="localCacheScope" value="SESSION"/>  
      <!-- 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用1般类型即可,比如 NULL、VARCHAR 或 OTHER。  -->  
      <setting name="jdbcTypeForNull" value="OTHER"/>  
    <!--   指定哪个对象的方法触发1次延迟加载。  -->  
      <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>  
    </settings>  

Related articles: