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

本文介绍如何在MyBatis中通过databaseId属性实现不同数据库类型的SQL适配,包括MySQL和Oracle示例,并展示了如何在Spring Boot环境中配置自动识别数据库类型的bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这里要用到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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值