데이터베이스에 따른 쿼리 관리 방법


DB 별로 Mapper XML 파일을 나누는 방식

resources/
├── mappers/
│   ├── oracle/UserMapper.xml
│   ├── postgresql/UserMapper.xml
│   ├── tibero/UserMapper.xml
@Configuration
public class MyBatisConfig {

    @Value("${db.type}") // ex) oracle, postgresql, tibero
    private String dbType;

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        // DB 타입에 따라 mapper 위치 변경
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(
            resolver.getResources("classpath:/mappers/" + dbType + "/*.xml")
        );

        return sessionFactory.getObject();
    }
}

db:
  type: tibero

DBMS마다 XML파일을 따로 두고, 실행 시 DB 종류에 따라 로드할 XML을 설정하는 방식이다. 실무에서 가장 많이 활용한다.


단일 XML 파일 - 동적 SQL로 분기

<select id="selectSysDate" resultType="string">
  SELECT
    <choose>
      <when test="_databaseId == 'oracle'">SYSDATE</when>
      <when test="_databaseId == 'tibero'">SYSDATE</when>
      <when test="_databaseId == 'postgresql'">CURRENT_TIMESTAMP</when>
      <otherwise>NOW()</otherwise>
    </choose>
  FROM DUAL
</select>

<configuration>
  <databaseIdProvider type="DB_VENDOR">
    <property name="Oracle" value="oracle"/>
    <property name="Tibero" value="tibero"/>
    <property name="PostgreSQL" value="postgresql"/>
  </databaseIdProvider>
</configuration>

databaseId를 활용하여 분기 처리를 통해 다른 SQL을 실행