MyBatis | Configuration File | Load an External Properties File

Code

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="hoge.properties">
    <property name="hoge" value="property tag"/>
    <property name="fuga" value="property tag"/>
    <property name="piyo" value="property tag"/>
  </properties>
</configuration>

hoge.properties

fuga=property file
piyo=property file

Main.java

package sample.mybatis;

import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            Properties prop = new Properties();
            prop.put("piyo", "Properties Class");

            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in, prop);
            Properties properties = factory.getConfiguration().getVariables();

            properties.forEach((key, value) -> {
                System.out.printf("%s=%s%n", key, value);
            });
        }
    }
}

Execution Result

hoge=property tag
fuga=property file
piyo=Properties Class

Explanation

  • Properties can be defined in the following places.
    • Define <property> tags inside the <properties> tag.
    • Define a properties file loaded by the <properties> tag.
    • Pass a Properties instance when creating SqlSessionFactory.
  • Each definition is loaded from top to bottom, and later definitions override earlier ones.
  • When importing another file with the <properties> tag, specify a resource file with the resource attribute or read a file by URL with the url attribute.
    • To use the url attribute, specify a value such as file:///C:/foo/bar/hoge.properties.
  • Imported properties can be referenced in the ${...} form.