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>

在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;
    }

我這里列出了所有支持的數據庫類型,實際使用的時候根據自己要用的數據庫添加就好。

在配置文件中正常配置數據庫信息就可以了。

如果使用的時候有問題,在配置文件中加上下邊配置

database:
  type: oracle

#mybatis設置
mybatis:
  mapper-locations: classpath*:mapper/*.xml
  configuration:
    database-id: ${database.type}
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

主要是database-id這個 。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

轉載來着 https://blog.csdn.net/qq_35981283/article/details/79503571


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM