Mybatis同时支持多种数据库(oracle 和MySQL)

里说下对多种数据库的支持,不是多个数据源。

这里要用到mybatis的databaseId。如下:

    <select id="isExist" resultType="Boolean" databaseId="mysql">
        SELECT EXISTS(SELECT 1 FROM `${db}`.test_table WHERE table_id=#{tableId} LIMIT 1)
    </select>

    <select id="isExist" resultType="Boolean" databaseId="oracle">
        SELECT COUNT(*) FROM ${db}."test_table " WHERE "table_id"=#{tableId}
    </select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在mapper.xml中加上databaseId就可以指定要用的sql,mybatis会根据链接过来的DataSource自动识别。

我这里使用的是spring boot,加上一个bean的配置:

    /**
     * 自动识别使用的数据库类型
     * 在mapper.xml中databaseId的值就是跟这里对应,
     * 如果没有databaseId选择则说明该sql适用所有数据库
     * */
    @Bean
    public DatabaseIdProvider getDatabaseIdProvider(){
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("Oracle","oracle");
        properties.setProperty("MySQL","mysql");
        properties.setProperty("DB2","db2");
        properties.setProperty("Derby","derby");
        properties.setProperty("H2","h2");
        properties.setProperty("HSQL","hsql");
        properties.setProperty("Informix","informix");
        properties.setProperty("MS-SQL","ms-sql");
        properties.setProperty("PostgreSQL","postgresql");
        properties.setProperty("Sybase","sybase");
        properties.setProperty("Hana","hana");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

我这里列出了所有支持的数据库类型,实际使用的时候根据自己要用的数据库添加就好。

在配置文件中正常配置数据库信息就可以了。

猜你喜欢

转载自blog.csdn.net/lldouble/article/details/80681347
今日推荐