Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set database login information from variable?

Tags:

java

mybatis

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.

like image 559
Petr Velký Avatar asked May 17 '11 11:05

Petr Velký


1 Answers

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.

1. In mybatis-config.xml

  • Add those property elements you want to set from inside Java to the <property> section.
  • Refer to those elements in the <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>

2. In Java

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);
like image 151
user905686 Avatar answered Oct 30 '22 02:10

user905686