SpringBoot 中JPA集成PostgreSql(详细步骤)
什么是JPA?(Java Persistence API)
Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.
Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.
Features
- Sophisticated support to build repositories based on Spring and JPA
- Support for Querydsl predicates and thus type-safe JPA queries
- Transparent auditing of domain class
- Pagination support, dynamic query execution, ability to integrate custom data access code
- Validation of
@Query
annotated queries at bootstrap time- Support for XML based entity mapping- JavaConfig based repository configuration by introducing@EnableJpaRepositories
.
国内说法
JPA 是指 Java Persistence API,即 Java 的持久化规范,一开始是作为 JSR-220 的一部分。 JPA 的提出,主要是为了简化 Java EE 和 Java SE 应用开发工作,统一当时的一些不同的 ORM 技术。 一般来说,规范只是定义了一套运作的规则,也就是接口,而像我们所熟知的Hibernate 则是 JPA 的一个实现(Provider)。
JPA 定义了什么,大致有:
- ORM 映射元数据,用来将对象与表、字段关联起来- 操作API,即完成增删改查的一套接口- JPQL 查询语言,实现一套可移植的面向对象查询表达式
PostgreSQL简介
PostGreSQL是一个功能强大的开源对象关系数据库管理系统(ORDBMS),号称世界上最先进的开源关系型数据库 经过长达15年以上的积极开发和不断改进,PostGreSQL已在可靠性、稳定性、数据一致性等获得了很大的提升。 对比时下最流行的 MySQL 来说,PostGreSQL 拥有更灵活,更高度兼容标准的一些特性。 此外,PostGreSQL基于MIT开源协议,其开放性极高,这也是其成为各个云计算大T 主要的RDS数据库的根本原因。
JPA中使用PostgreSQL
一、添加依赖包
Spring Boot Mavn项目 Pom.xml文件中添加依赖包
<!--jpa与postgresql-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
二、配置PostgreSQL和jpa
在application-dev.yml(开发环境)中添加如下:
server:
port: 8088
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://192.168.0.30:5432/thingsboard
username: root
password: 123456
hikari:
minimum-idle: 5
maximum-pool-size: 15
auto-commit: true
idle-timeout: 30000
connection-timeout: 60000
validation-timeout: 10000
jpa:
show-sql: true
redis:
host: 127.0.0.1
database: 0
port: 6379
password:
lettuce:
pool:
max-active: 10
max-idle: 10
max-wait: 5ms
tb:
url: https://nybx-ljyz.cpic.com.cn/aims
logging:
level: debug
le