相關(guān)文章:使用properties文件保存配置屬性值
可以在mybatis-config.xml配置文件中創(chuàng)建多個(gè)數(shù)據(jù)源,方便切換欲操作的數(shù)據(jù)庫(kù)腿短。
創(chuàng)建db.properties屬性文件仅淑,內(nèi)容如下:
mysql1.driver=com.mysql.cj.jdbc.Driver
mysql1.url=jdbc:mysql://localhost:3306/test?useSSL=false
mysql1.username=root
mysql1.password=123456
mysql2.driver=com.mysql.cj.jdbc.Driver
mysql2.url=jdbc:mysql://localhost:3306/xxxx?useSSL=false
mysql2.username=root
mysql2.password=123456
配置文件mybatis-config.xml代碼如下:
<?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="db.properties"></properties>
<!--默認(rèn)使用id="mysql1"的environment-->
<environments default="mysql1">
<!--環(huán)境配置一-->
<environment id="mysql1">
<!--事務(wù)管理配置-->
<transactionManager type="JDBC"/>
<!--數(shù)據(jù)源配置-->
<dataSource type="POOLED">
<property name="driver" value="${mysql1.driver}"/>
<property name="url" value="${mysql1.url}"/>
<property name="username" value="${mysql1.username}"/>
<property name="password" value="${mysql1.password}"/>
</dataSource>
</environment>
<!--環(huán)境配置二-->
<environment id="mysql2">
<!--事務(wù)管理配置-->
<transactionManager type="JDBC"/>
<!--數(shù)據(jù)源配置-->
<dataSource type="POOLED">
<property name="driver" value="${mysql2.driver}"/>
<property name="url" value="${mysql2.url}"/>
<property name="username" value="${mysql2.username}"/>
<property name="password" value="${mysql2.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--這里的resource對(duì)應(yīng)上一步自動(dòng)生成的mapping/UserinfoMapper.xml文件-->
<mapper resource="mapping/UserinfoMapper.xml"/>
</mappers>
</configuration>
配置<environments default="mysql1">代表默認(rèn)使用id="mysql1"的environment称勋,以后也是在這里切換欲操作的數(shù)據(jù)庫(kù)實(shí)例,從而達(dá)到配置多數(shù)據(jù)源的目的涯竟。