Petr Velký Petr Velký - 1 year ago 54
Java Question

How to set database login information from variable?

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

. 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.

Answer Source

The configuration xml file supports a <properties> element. You can either point to an external file (through the resource attribute) or define each <property> directly in the xml.

Properties can be referenced elsewhere in the Mybatis config and mapper xml files with ${property} syntax like this (from page 12 of the documentation):

<properties resource="org/mybatis/example/"> 
  <property name="username" value="dev_user"/> 
  <property name="password" value="F2Fa3!33TYyg"/> 

<dataSource type="POOLED"> 
  <property name="driver" value="${driver}"/> 
  <property name="url" value="${url}"/> 
  <property name="username" value="${username}"/> 
  <property name="password" value="${password}"/> 

Note that property elements override any properties defined in the file.