MyBatis之适配不同数据库

DBIdEnum.class
下面的productName可以通过SqlSession获取,获取方式:Java之获取SqlSession和ProductName

package com.qdbeiqi.bpm.domain.visitor.db.adaptation;

import lombok.AllArgsConstructor;

/**
 * @author Jalon
 * @since 2023/11/2 17:20
 **/
@AllArgsConstructor
public enum DBIdEnum {
    SqlServer("Microsoft SQL Server", "sqlserver"),
    KingBase("KingbaseES", "kingbase");

    public static DBIdEnum getEnumer(String _databaseId) {
        DBIdEnum[] values = DBIdEnum.values();
        for (DBIdEnum v : values) {
            if (_databaseId.equals(v.getValue())) {
                return v;
            }
        }
        throw new RuntimeException("DBIdEnum中找不到给定的_databaseId:" + _databaseId);
    }

    // 数据库厂商提供的productName
    private String name;
    // 根据productName自定义应用中使用的值
    private String value;

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }
}

MyBatisConfig.class

package com.qdbeiqi.bpm.domain.visitor.db.adaptation;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @author Jalon
 * @since 2023/11/2 17:56
 **/
@Configuration
public class MyBatisConfig {

    @Bean
    public DatabaseIdProvider databaseIdProvider() throws Exception {
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties props = new Properties();
        DBIdEnum[] values = DBIdEnum.values();
        for (DBIdEnum v : values) {
            props.put(v.getName(), v.getValue());
        }
        databaseIdProvider.setProperties(props);
        return databaseIdProvider;
    }
}

通过if判断

<if test="_databaseId == 'sqlserver'">
       CONVERT(VARCHAR(10), visit_time, 23)
if>
<if test="_databaseId == 'kingbase'">
    to_char(visit_time, 'YYYY-MM-DD')
if>

通过标签databaseId

<select id="" databaseId="sqlserver" resultType="">
select>
<select id="" databaseId="kingbase" resultType="">
select>

你可能感兴趣的:(Java,mybatis,数据库,java,适配,databaseId)