Database ( DB )/ibatis, mybatis

[mybatis] JAVA로 config 설정

노루아부지 2019. 8. 11. 10:23
반응형
public static SqlSession getSqlSession(String prefix) throws Exception {
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(createSqlMap(prefix));
    SqlSession sqlSession = factory.openSession(false);
        
    return sqlSession;
}
 
private static InputStream createSqlMap(String prefix) throws Exception {
        
    Reader reader = Resources.getResourceAsReader("properties/wow.properties");
    Properties properties = new Properties();
    properties.load(reader);
        
    StringBuffer rtn = new StringBuffer();
    rtn.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    rtn.append("<!DOCTYPE configuration");
    rtn.append("    PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\"");
    rtn.append("    \"http://mybatis.org/dtd/mybatis-3-config.dtd\">");
    rtn.append("<configuration>");
    rtn.append("    <properties resource=\"properties/wow.properties\" />");
    rtn.append("    <environments default=\"development\">");
    rtn.append("        <environment id=\"development\">");
    rtn.append("            <transactionManager type=\"JDBC\" />");
    rtn.append("            <dataSource type=\"POOLED\">");
    rtn.append("                <property name=\"driver\" value=\"" + properties.getProperty(prefix + ".jdbc.driverClassName") + "\" />");
    rtn.append("                <property name=\"url\" value=\"" + properties.getProperty(prefix + ".jdbc.url") + "\" />");
    rtn.append("                <property name=\"username\" value=\"" + properties.getProperty(prefix + ".jdbc.user") + "\" />");
    rtn.append("                <property name=\"password\" value=\"" + properties.getProperty(prefix + ".jdbc.password") + "\" />");
    rtn.append("            </dataSource>");
    rtn.append("        </environment>");
    rtn.append("    </environments>");
    rtn.append("    <mappers>");
    rtn.append("        <mapper resource=\"com/insa/" + properties.getProperty(prefix + ".jdbc.databaseType") + "/Common.xml\" />");
    rtn.append("    </mappers>");
    rtn.append("</configuration>");
        
    return new ByteArrayInputStream( rtn.toString().getBytes() );
}
 
public static void main( String[] args ) throws Exception {
    Reader reader = Resources.getResourceAsReader("properties/wow.properties");
    Properties properties = new Properties();
    properties.load(reader);
        
    SqlSession wowSession = DatabaseConfig.getSqlSession("wow");
 
    wowSession.delete("Common.deleteTable", paramMap);
 
    wowSession.commit();
    wowSession.close();
}
728x90
반응형
loading