Mybatis-Plus支持多种数据库

使用Mybatis-Plus进行数据库的访问,但是由于不同的数据库有不同的方言,所以需要进行适配。

有2种实现方式:

  • databaseId方式
  • Mapper Location方式

指定databaseId方式

通过databaseId指定所使用的数据库,选择同步的SQL。

Mapper.xml设置

默认*Mapper.xml文件的路径在 resources/mapper/

默认*Mapper.xml文件的路径在 resources/mapper/

   
	<select id="listAll" resultType="com.sinopec.exploit.model.T1Entity" databaseId="mysql">
        SELECT *
        FROM t2

    select>
  
    <select id="listAll" resultType="com.sinopec.exploit.model.T1Entity" databaseId="pgsql">
        SELECT *
        FROM t3

    select>

  
    <select id="listAll" resultType="com.sinopec.exploit.model.T1Entity" databaseId="kes">
        SELECT *
        FROM t3

    select>

	
    <select id="listAll" resultType="com.sinopec.exploit.model.T1Entity" >
        SELECT *
        FROM t4

    select>


	
    <select id="selectOne" resultType="com.sinopec.exploit.model.T1Entity" >
        SELECT *
        FROM t5

    select>

databaseId 用于指定SQL适用于哪个数据库,如果没有设置,则表示适用于所有数据库。Mybatis在选择SQL时,先根据yaml中配置的 databaseId值与*Mapper.xml中SQL的databaseId匹配,如果匹配则选择,如果不匹配,则选择没有设置databaseId的SQL,如果仍然未匹配上,则报错。

在代码中可以引用变量 _databaseId 表示databaseId。

指定databaseId

指定databaseId有多种方式:

  • 直接配置

    mybatis-plus:
      configuration:
        database-id: mysql
    
  • 自动侦测

    通过DatabaseIdProvider获取DatabaseProductName

        @Bean
        public DatabaseIdProvider databaseIdProvider() {
            VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
            Properties properties = new Properties();
            properties.put("Oracle","oracle");
            properties.put("MySQL","mysql");
            properties.put("PostgreSQL","pgsql");
            databaseIdProvider.setProperties(properties);
            return databaseIdProvider;
        }
    

OiO产品采用yaml配置方式。

databaseId值设置

  • Mysql:mysql
  • Oracle:oracle
  • postgresql:pgsql
  • 人大金仓:kes
  • 达梦:dm

当前OiO产品实现了mysql、postgresql、人大金仓的兼容。

后续可能会扩展到达梦数据库,待定。

Mapper Location方式

1、在resources里放置多个数据库的目录,然后不同目录放置不同的方言语句。

Mybatis-Plus支持多种数据库_第1张图片

2、指定Mapper.xml文件

mybatis-plus:
  # MyBatis Mapper所对应的XML文件位置
  mapper-locations: classpath:/mapper/mysql/*Mapper.xml

确定方案

Mapper Location方式虽然逻辑清晰的区分多种数据库,但是再扩展多一种方式的时候,不能快速确定哪些SQL 是不一致的。

因此选择databaseId 方式。

以前部分服务采用了Mapper Location方式,因此需要调整为databaseId 方式。

IDEA怎么比较2个文件

1、选择一个要比较的文件

2、按住CTRL,选择另外一个文件。

3、点击右键,选择Compare Files 命令,比较2个文件差异。

你可能感兴趣的:(数据库,mybatis,多数据库)