配置MyBatis时,一般都会将数据库参数放在配置文件中,如jdbc.properties,然后通过载入配置文件的方式获取参数:
<?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="mybatis/jdbc.properties"/>
-->
<typeAliases>
<typeAlias alias="userTpm" type="com.test.tool.common.tpm.UserTpm"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/test/tool/dsm/UserDsm.xml"/>
</mappers>
</configuration>
jdbc.properties文件内容如下:
- jdbc.driver=xxxx
- jdbc.url=xxxxxx
- jdbc.username=xxxx
- jdbc.password=xxxx
现在想要 动态修改 数据库连接的参数 ,不使用jdbc.properties中的参数,代码如下:
- //动态配置数据库参数
- Properties properties = new Properties();
- properties.setProperty("jdbc.driver", "动态设置");
- properties.setProperty("jdbc.url", "动态设置");
- properties.setProperty("jdbc.username", "动态设置");
- properties.setProperty("jdbc.password", "动态设置");
- //加载mybatis配置文件和映射文件
- String resource = "mybatis/mybatis-config.xml";
- Reader reader = Resources.getResourceAsReader(resource);
- SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
- SqlSessionFactory factory = builder.build(reader, properties);
- SqlSession session = factory.openSession();
- //获取对象
- userDsm = session.getMapper(UserDsm.class);
- ......
- userDsm.addUser(...);
- ......
转载于:https://my.oschina.net/u/580135/blog/612288