概述
本人最近接到一个任务,将一个系统改成同时兼容Oracle和PostgreSQL(原来是仅支持Oracle)。虽然大部分的sql语句通用,但是还有许多语法存在差异,所以我们可以通过mybatis自身提供的databaseIdProvider解决这个问题,这里记录一下过程。
databaseId属性: 如果配置了 databaseIdProvider,MyBatis 会加载所有的不带 databaseId 或匹配当前 databaseId 的语句;如果带或者不带的语句都有,则不带的会被忽略。新增,修改和删除都有这个属性。
配置
pom依赖
org.springframework.boot
spring-boot-starter-web
com.oracle
ojdbc6
11.2.0.3
org.postgresql
postgresql
9.4.1212
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
com.alibaba
fastjson
1.2.16
com.alibaba
druid-spring-boot-starter
1.1.10
配置文件
通过配置文件开启mysql支持或者postgresql支持
application.yml
# 切换对应的环境 postgresql mysql
spring:
profiles:
active: postgresql
# mybatis配置
mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: com.valten.**.model
# showSql 控制台打印sql日志
logging:
level:
com:
valten:
dao: debug
application-mysql.yml
# 端口
server:
port: 8001
# 数据源配置
spring:
datasource:
hikari:
jdbc-url: jdbc:mysql://127.0.0.1:3306/test?&useSSL=false
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
application-postgresql.yml
# 端口
server:
port: 8002
# 数据源配置
spring:
datasource:
hikari:
jdbc-url: jdbc:postgresql://127.0.0.1:5432/test
driver-class-name: org.postgresql.Driver
username: root
password: 123456
注意 SpringBoot1和2的数据原配置写法区别
数据源配置类
@Configuration
public class DataSourceConfig {
@Value("${mybatis.mapper-locations}")
private String mapperLocations;
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties("spring.datasource.hikari")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public DatabaseIdProvider databaseIdProvider() {
DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties p = new Properties();
p.setProperty("Oracle", "oracle");
p.setProperty("MySQL", "mysql");
p.setProperty("PostgreSQL", "postgresql");
p.setProperty("DB2", "db2");
p.setProperty("SQL Server", "sqlserver");
databaseIdProvider.setProperties(p);
return databaseIdProvider;
}
@Primary
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setDatabaseIdProvider(databaseIdProvider());
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
return factoryBean;
}
}
UserMapper.xml
select
account
dep_code
from SYS_USER
where ID = #{id,jdbcType=CHAR}