PostgreSQL是一种特性非常齐全的自由软件的对象-关系型数据库管理系统(ORDBMS),是以加州大学计算机系开发的POSTGRES,4.2版本为基础的对象关系型数据库管理系统。POSTGRES的许多领先概念只是在比较迟的时候才出现在商业网站数据库中。PostgreSQL支持大部分的SQL标准并且提供了很多其他现代特性,如复杂查询、外键、触发器、视图、事务完整性、多版本并发控制等。同样,PostgreSQL也可以用许多方法扩展,例如通过增加新的数据类型、函数、操作符、聚集函数、索引方法、过程语言等。另外,因为许可证的灵活,任何人都可以以任何目的免费使用、修改和分发PostgreSQL。——上述介绍来自百度百科
PostgreSQL号称是 世界上最先进的开源数据库
,如下图。
本文属于入门介绍,从零初始化一个SpringBoot项目,集成PostgreSQL并使用JPA和MyBatis两种方式对其进行操作。这里只记录PostgreSQL相关操作,项目创建过程不详细介绍,类似流程可参考<<Spring Boot:Idea从零开始初始化后台项目>>。PostgreSQL数据库使用上午构建的Docker容器,构建过程可参考<<Docker案例:Mac系统构建PostgreSQL容器及使用>>,下面的案例也针对这篇文章中创建的user
表展开。
1 项目依赖
当前项目使用了如下一些依赖包:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
implementation 'org.apache.commons:commons-lang3:3.10'
implementation 'com.alibaba:fastjson:1.2.71'
implementation 'com.github.javafaker:javafaker:1.0.2'
implementation 'com.google.guava:guava:29.0-jre'
implementation 'com.github.pagehelper:pagehelper-spring-boot-starter:1.2.13'
runtimeOnly 'org.postgresql:postgresql'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
2 项目配置
有两个配置文件application.properties
和application-dev.properties
。前者主要配置通用项并指定环境配置文件,后者为当前环境的配置文件(其中数据库配置项的值需参考<<Docker案例:Mac系统构建PostgreSQL容器及使用>>中的设置)。配置文件内容如下:
application.properties
spring.profiles.active=dev
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
application-dev.properties
server.port=8280
#数据库基本信息配置
spring.datasource.url=jdbc:postgresql://localhost:5433/pg-db-crane
spring.datasource.username=pg-user-crane
spring.datasource.password=crane
spring.datasource.driverClassName=org.postgresql.Driver
spring.jpa.show-sql=true
#JPA相关配置
spring.jpa.database=postgresql
#spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
logging.config=classpath:logback-dev.xml
3 JPA操作
为简单模拟操作,创建实体类、数据库持久化操作类和一个控制器类。
3.1 构造实体
根据user
表构造User
实体类,完整代码如下:
@Entity
@Table(name = "user", schema = "public")
@Where(clause = "id > 0")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name", nullable = false)
private String name;
private String phone;
private String email;
private String position;
private String address;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name