Springboot集成Postgresql数据库

950 阅读3分钟

1. 背景介绍

在大多数情况下,一般会采用MySQL作为Springboot项目的关系数据库,而本文介绍了在Springboot项目中利用Mybatis的XML配置方式集成Postgresql,并通过具体的实例说明集成过程中的关键点。

  • MyBatis是一款优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
  • PostgreSQL 是一种功能强大且开源的关系型数据库管理系统(RDBMS),它提供了许多高级功能,例如复杂查询、事务、触发器、视图等。PG支持插件扩展,例如引入PostGIS插件支持地理信息系统 (GIS)的存储。

2. 引入Maven依赖

  • 引入maven依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<!--postgresql-->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.3.1</version>
</dependency>
  • 增加yml的数据源配置
datasource:
  driver-class-name: org.postgresql.Driver
  url: jdbc:postgresql://ip:port/table_name
  username: username
  password: password
  • 增加yml的mybatis-plus配置 这里需要注意表名和字段名是下划线分隔的,而Java类的属性是驼峰命名的,因此要开启map-underscore-to-camel-case配置。
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-field: isDelete # 全局逻辑删除的实体字段名
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

3. 数据库表创建

  • 创建数据库和数据表sql命令
-- 创建测试数据库
create database test_db;

-- 创建测试表
create test_table
(
    id                  bigserial          primary key,
    resource_id         bigint                      not null,
    user_id             bigint                      not null,
    operation_type      varchar(255)                not null,
    create_time          timestamp without time zone    default current_timestamp    not null,
    update_time         timestamp without time zone    default current_timestamp    not null,
    end_time            timestamp without time zone    null,
    operation_status    varchar(255)                default 'not-started'     not null,
    is_delete           smallint                    default  0                not null
);
  • 增加时间自动更新函数
create or replace function update_updatetime()
    returns trigger as $$
begin
    new.update_time := current_timestamp;
    return new;
end;
$$ language plpgsql;

drop trigger if exists update_trigger on test_table;
create trigger update_time_trigger
    before update on test_table
    for each row
execute function update_updatetime();
  • 为表和字段添加comment
comment on table test_table is '...';
comment on column test_table.resource_id is '';
comment on column test_table.user_id is '...';
comment on column test_table.operation_type is '...';
comment on column test_table.start_time is '...';
comment on column test_table.end_time is '...';
comment on column test_table.operation_status is '...';
comment on column test_table.is_delete is '逻辑删除';

4. MyBatis代码生成

MyBatis提供了开发上的便捷,但是依然需要写大量的xml配置,并且很多都是CRUD级别的(这便有了很多重复性的工作),所以为了减少重复编码,衍生出了MyBatis代码生成工具, 比如CodeGenerator等。其它开发IDE也开始出现封装一些工具和插件来生成代码生成工具等,例如IDEA编辑器提供插件支持MyBatis代码自动生成。代码生成后应该将文件移到项目的对应位置。

image.png

  • 选择生成代码存储的位置等

image.png

  • 一些详细配置项和生成代码文件

image.png

5. 集成结果测试

  • controller层测试代码
/**
 * 根据 id 获取
 *
 * @param id
 * @return
 */
@PostMapping("/get/vo")
public BaseResponse<TestTableVO> getTestTableVOById(long id, HttpServletRequest request) {
    if (id <= 0) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    TestTable testTable = testTableService.getById(id);
    if (testTable == null) {
        throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
    }
    return ResultUtils.success(testTableService.getTestTableVO(testTable, request));
}
  • Swagger接口文档中调试接口

image.png