背景:
之前用spring boot+mybatis+oracle,现在要改成spring boot_mybatis+postgresql。
为了想让一套代码即可以使用oracle库运行,也可以使用postgresql运行。所以需要进行代码修改。
访问postgresql
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=123456
spring.datasource.driverClassName=org.postgresql.Driver
mybatis支持两类数据库
在Application类中加入配置Bean
@Bean
public DatabaseIdProvider getDatabasedIdProvider(){
DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties properties = new Properties();
properties.setProperty("Oracle","oracle");
properties.setProperty("MySQL","mysql");
properties.setProperty("DB2","d2");
properties.setProperty("PostgreSQL","pg");
databaseIdProvider.setProperties(properties);
return databaseIdProvider;
}
然后在mapper的xml中直接使用databaseId就可以了,databaseId就是配置Bean中添加的如pg、oracle之类的。
<insert id="insert" databaseId="pg" parameterType="com.gxdgroup.common.entity.User">
<insert id="insert" databaseId="oracle" parameterType="com.gxdgroup.common.entity.User">
Postgresql中类似oracle的方法
1、nvl
postgresql中有类似的方法 coalesce。
2、把逗号分隔的字符串拆分
select regexp_substr(t6.menu_ids,'[^,]+',1,level) from dual
connect by regexp_substr(t6.menu_ids,'[^,]+',1,level) is not null
select cast(regexp_split_to_table(t6.menu_ids,E',') as integer)
cast ..as integer是因为我需要integer类型,作为强制转换。
3、序列
create sequence eva_seq
minvalue 0
increment 1
maxvalue 9223372036854775807
start 1
cache 30
;
select nextval('eva_seq');
4、存储过程
CREATE OR REPLACE FUNCTION totalRecords ()
RETURNS integer AS $total$
declare
total integer;
BEGIN
SELECT count(*) into total FROM EMPLOYEES;
RETURN total;
END;
$total$ LANGUAGE plpgsql;
5、postgresql判断表或序列是否存在
<select id="isTableExist" databaseId="pg" parameterType="String" resultType="Integer">
select count(*)
from pg_class where relname=#{tableName}
</select>