这里重点描述从 Mysql 迁移到 PostgreSql 中重点注意事项。以及在普通的业务逻辑中,应该注意的事项。
mysql 的撰写
create table wk_course (course_id BIGINT unsigned NOT NULL AUTO_INCREMENT COMMENT '课程id',course_name varchar(255) NOT NULL COMMENT '课程',gmt_create DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT '记录创建时间',gmt_modified DATETIME DEFAULT CURRENT_TIMESTAMP NULL COMMENT '记录修改时间',PRIMARY KEY (course_id),UNIQUE KEY `wk_course_unique` (`course_name`)) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8mb4 COMMENT='课程表';
PostgreSql
create table wk_course (course_id BIGSERIAL NOT NULL ,course_name varchar(255) NOT NULL ,gmt_create timestamp(0) without time zone DEFAULT CURRENT_TIMESTAMP ,gmt_modified timestamp(0) without time zone DEFAULT CURRENT_TIMESTAMP ,PRIMARY KEY (course_id),constraint wk_course_unique unique (course_name)) ;comment on table wk_course is '课程表';comment on column wk_course.course_id is '课程id';comment on column wk_course.course_name is '课程';comment on column wk_course.gmt_create is '记录创建时间';comment on column wk_course.gmt_modified is '记录修改时间';
差距
PostgreSql
中没有 unsigned
Mysql
的日期时间类型,转换成PostgreSql
的 timestamp(0) without time zone
MySql
是AUTO_INCREMENT
,PostgreSql
用:SMALLSERIAL
、SERIAL
和 BIGSERIAL
类型PostgreSql: constraint wk_student_scores_unique unique (student_id,course_id)
这里是特殊性
public schema
不建议使用外键
不建议自建函数与校验规则,这部分交给 Java 程序来处理。
不建议使用数据库触发器,这会使得数据处理逻辑复杂,不便于调试
不建议使用文件类型的字段
系统中以前为Mysql
生成的代码,在代码不做修改的前提下,如何兼容PostgreSql
呢?
兼容自增
在PostgreSql
中创建一个函数
create or replace function LAST_INSERT_ID()returns bigint as $$beginreturn lastval();end; $$language plpgsql;
现在框架的底层可以支持 Mysql 与 PostgreSql,并且做了单元测试。如果分别测试两种数据库呢?
修改下面要连接的数据库,然后执行 test 命令,就进行了自动化单元测试。
#spring:# datasource:# driver-class-name: com.mysql.cj.jdbc.Driver# password: Mysql@root123# url: jdbc:mysql://127.0.0.1:3306/wk_example?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai# username: rootspring:datasource:driver-class-name: org.postgresql.Driverpassword: exampleurl: jdbc:postgresql://127.0.0.1:5432/testusername: postgresflyway:locations: classpath:db/migration-pgenabled: true