MyBatis配置文件之数据源的配置方式

MyBatis配置文件中数据源的几种配置方式

第一种方式

第一种方式就是直接写mybatis-config配置文件中的dataSource标签下的property标签中,如:

		
			
			
			
			
		

第二种方式

第二种方式就是有外部文件database.properties然后引入到MyBatis配置文件中。
1、database.properties如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///jdbcdemo20190804?useUnicode=true&characterEncoding=UTF-8
userName=root
pwd=root

2、然后再MyBatis配置文件的properties标签中引入:


3、然后修改dataSource标签下的property标签中value属性的值为${ },大括号中分别写对应的database.properties的key值。如:


整个配置文件如下:



 
 <configuration>
 	
 	<properties resource="database.properties">properties>
 	
 	
 	<settings>
 		<setting name="logImpl" value="STDOUT_LOGGING"/>
 	settings>
 	
 	
 	
 	<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="${pwd}"/>
 			dataSource>
 		environment>
 	environments>
 	
 	
 	<mappers>
 		<mapper resource="mapper/EmpMapper.xml"/>
 		
 	mappers>
 	
 configuration>

第三种方式

第三种方式是不需要外部文件database.properties,而是把数据源的配置写在mybatis-config的properties标签中,然后再在dataSource的property标签中引用。
1、properties标签编写如下:

	
 		
 		
 		
 		
 	

2、通过dataSource标签下的property标签中value属性添加引用。 如:


整个配置文件如下:



 
 <configuration>
 	
 	<properties>
 		<property name="driver" value="com.mysql.jdbc.Driver"/>
 		<property name="url" value="jdbc:mysql:///jdbcdemo20190804"/>
 		<property name="userName" value="root"/>
 		<property name="pwd" value="root"/>
 	properties>
 	
 	
 	<settings>
 		<setting name="logImpl" value="STDOUT_LOGGING"/>
 	settings>
 	
 	
 	
 	<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="${pwd}"/>
 			dataSource>
 		environment>
 	environments>
 	
 	
 	<mappers>
 		<mapper resource="mapper/EmpMapper.xml"/>
 		
 	mappers>
 	
 configuration>

引出的问题(优先级)

第二种方式和第三种方式都是通过properties标签来写的,如果第二种方式和第三种方式一起使用了,那么是那种方式优先呢?
什么意思,就是,既有database.properties如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///jdbcdemo20190804?useUnicode=true&characterEncoding=UTF-8
userName=root
pwd=root

又有配置文件如下:



 
 
 	
 	
 		
 		
 		
 		
 	
 	
 	
 	
 		
 	
 	
 	
 	
 	
 		
 			
 			
 			
 				
 				
 				
 				
 			
 		
 	
 	
 	
 	
 		
 		
 	
 	
 

配置文件中同时使用了"第二种方式"和"第三种方式"。
那么这两种方式谁更优先呢?
测试发现:resource属性值的优先级高于property子节点配置的值。(即第二种方式优先级高于第三种方式。)

你可能感兴趣的:(MyBatis)