spring boot mybatis 支持oracle postgresql

阅读数:171 评论数:0

跳转到新版页面

分类

python/Java

正文

背景:

之前用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>



相关推荐

1、使用selectKey标签 &lt;insert id="addLoginLog" parameterTyp

一、概述 springboot中有两种方式使用kafka时,直接使用kafka-client连接kafka服务;另一种是使用spring-kafka框架来连接kafka。 1、版本兼容 使用时要注意版

当然可以自己写redis的工具类,或者使用第三方开源jar包或代码,这里使用spring boot的集成类。 一、pom依赖 <dependency> <gro

websocket协议基于tcp的网络协议,它实现浏览器与器全双工通信。 spring boot2 +websocket 1、添加依赖 <pre clas

出现这个错误,是因为mybatis默认OGNL解析参数,所以会自动采用对象树形式取String.xxx值。 解决方法: 方法1:在方法中提前定义 <pre c

&lt;if test="extraSql != null and extraSql !=''"&gt; AND ${ext

一、概述 mybatis原来是apache的一个开源项目,叫做ibatis,2010年由apache迁移到了google code,并且改名为mybatis。2013年迁移到github。 mybat

(1)Executor 执行增删改查操作

实际开发中,有时候需要把当前插入的数据id取出来,但又不想再去查一遍. mybatis提供了两种返回insert方法后的主键的方法 : 1、根据useGeneratedKeys获取

一、概述 一个项目使用多个数据库(无论是主从复制--读写分离还是分布式数据库结构)的重要性变得越来越明显,整合的多数据源有两种方式:分包和aop。 1、SqlSessionTemplate SqlSe