I am using MyBatis in a Java project. I know that database access information such as host, database name, username and password are stored in configuration.xml
. But I would like to know if I can set these login information from inside my Java program.
It's because my application is accessing different databases on different addresses and I am configuring them in the application. Please help me.
Because the existing answers were not enough to help me out with the same problem, here is my solution. It works with myBatis 3.2.1.
mybatis-config.xml
<property>
section.<dataSource>
section using ${*property*}
as value.<?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>
<property name="url" value=""/>
<property name="username" value=""/>
<property name="password" value=""/>
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
...
</mappers>
</configuration>
Create a Properties
object, add the properties you selected to set manually and pass it to the build()
method when obtaining the SqlSessionFactory
:
Properties properties = new Properties();
properties.setProperty("username", "myUser");
properties.setProperty("password", "myPwd");
properties.setProperty("url", "myConnectionURL");
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, properties);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With