相关文章推荐
微醺的大象  ·  android MediaPlayer ...·  1 年前    · 
慈祥的消炎药  ·  javascript - Uncaught ...·  1 年前    · 

SpringBoot 整合 PostGreSQL


一、PostGreSQL简介

PostGreSQL是一个功能强大的开源对象关系数据库管理系统(ORDBMS),号称 世界上最先进的开源关系型数据库。 经过长达15年以上的积极开发和不断改进,PostGreSQL已在可靠性、稳定性、数据一致性等获得了很大的提升。

对比时下最流行的 MySQL 来说,PostGreSQL 拥有更灵活,更高度兼容标准的一些特性。 此外,PostGreSQL基于MIT开源协议,其开放性极高,这也是其成为各个云计算大T 主要的RDS数据库的根本原因。

从DBEngine的排名上看,PostGreSQL排名第四,且保持着高速的增长趋势,非常值得关注。 这篇文章,以整合SpringBoot 为例,讲解如何在常规的 Web项目中使用 PostGreSQL。


二、关于 SpringDataJPA

JPA 是指 Java Persistence API ,即 Java 的持久化规范,一开始是作为 JSR-220 的一部分。 JPA 的提出,主要是为了简化 Java EE 和 Java SE 应用开发工作,统一当时的一些不同的 ORM 技术。 一般来说,规范只是定义了一套运作的规则,也就是接口,而像我们所熟知的Hibernate 则是 JPA 的一个实现(Provider)。

JPA 定义了什么,大致有:

  • ORM 映射元数据,用来将对象与表、字段关联起来

  • 操作API,即完成增删改查的一套接口

  • JPQL 查询语言,实现一套可移植的面向对象查询表达式

要体验 JPA 的魅力,可以从Spring Data JPA 开始。

SpringDataJPA 是 SpringFramework 对 JPA 的一套封装,主要呢,还是为了简化数据持久层的开发。 比如:

  • 提供基础的 CrudRepository 来快速实现增删改查

  • 提供一些更灵活的注解,如@Query、@Transaction

基本上,SpringDataJPA 几乎已经成为 Java Web 持久层的必选组件。更多一些细节可以参考官方文档:

https://docs.spring.io/spring-data/jpa/docs/1.11.0.RELEASE/reference/html

接下来的篇幅,将演示 JPA 与 PostGreSQL 的整合实例。


三、整合 PostGreSQL

这里假定你已经安装好数据库,并已经创建好一个 SpringBoot 项目,

接下来需添加依赖:

A. 依赖包

  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-data-jpa</artifactId>

  4. <version>${spring-boot.version}</version>

  5. </dependency>


  6. <dependency>

  7. <groupId>org.postgresql</groupId>

  8. <artifactId>postgresql</artifactId>

  9. <scope>runtime</scope>

  10. </dependency>

通过 spring-boot-stater-data-jpa ,可以间接引入 spring-data-jpa 的配套版本;

为了使用 PostGreSQL,则需要引入 org.postgresql.postgresql 驱动包。


B. 配置文件

编辑 application.properties ,如下:

  1. ## 数据源配置 (DataSourceAutoConfiguration & DataSourceProperties)

  2. spring.datasource.url=jdbc:postgresql://localhost:5432/appdb

  3. spring.datasource.username=appuser

  4. spring.datasource.password=appuser


  5. # Hibernate 原语

  6. spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect


  7. # DDL 级别 (create, create-drop, validate, update)

  8. spring.jpa.hibernate.ddl-auto = update

其中, spring.jpa.hibernate.ddl-auto 指定为 update,这样框架会自动帮我们创建或更新表结构。


C. 模型定义

我们以书籍信息来作为实例,一本书会有标题、类型、作者等属性,对应于表的各个字段。

这里为了演示多对一的关联,我们还会定义一个Author(作者信息)实体,书籍和实体通过一个外键(author_id)关联。

Book 类

  1. @Entity

  2. @Table(name = "book")

  3. public class Book extends AuditModel{


  4. @Id

  5. @GeneratedValue(strategy=GenerationType.IDENTITY)

  6. private Long id;


  7. @NotBlank

  8. @Size(min = 1, max = 50)

  9. private String type;


  10. @NotBlank

  11. @Size(min = 3, max = 100)

  12. private String title;


  13. @Column(columnDefinition = "text")

  14. private String description;


  15. @Column(name = "fav_count")

  16. private int favCount;


  17. @ManyToOne(fetch = FetchType.LAZY, optional = false)

  18. @JoinColumn(name = "author_id", nullable = false)

  19. private Author author;


  20. //省略 get/set

这里,我们用了一系列的注解,比如 @Table、@Column 分别对应了数据库的表、列。

@GeneratedValue 用于指定ID主键的生成方式, GenerationType.IDENTITY 指采用数据库原生的自增方式, 对应到 PostGreSQL则会自动采用 BigSerial 做自增类型(匹配Long 类型)

@ManyToOne 描述了一个多对一的关系,这里声明了其关联的"作者“实体,LAZY 方式指的是当执行属性访问时才真正去数据库查询数据;

@JoinColumn 在这里配合使用,用于指定其关联的一个外键。

Book 实体的属性:

属性 描述
id 书籍编号
type 书籍分类
title 书籍标题
description 书籍描述
favCount 收藏数
author 作者


Author信息

  1. @Entity

  2. @Table(name = "author")

  3. public class Author extends AuditModel{


  4. @Id

  5. @GeneratedValue(strategy=GenerationType.IDENTITY)

  6. private Long id;


  7. @NotBlank

  8. @Size(min = 1, max = 100)

  9. private String name;


  10. @Size(max = 400)

  11. private String hometown;


审计模型

注意到两个实体都继承了AuditModel这个类,这个基础类实现了"审计"的功能。

审计,是指对数据的创建、变更等生命周期进行审阅的一种机制, 通常审计的属性包括 创建时间、修改时间、创建人、修改人等信息

AuditModel 的定义如下所示:

  1. @MappedSuperclass

  2. @EntityListeners(AuditingEntityListener.class)

  3. public abstract class AuditModel implements Serializable {

  4. @Temporal(TemporalType.TIMESTAMP)

  5. @Column(name = "created_at", nullable = false, updatable = false)

  6. @CreatedDate

  7. private Date createdAt;


  8. @Temporal(TemporalType.TIMESTAMP)

  9. @Column(name = "updated_at", nullable = false)

  10. @LastModifiedDate

  11. private Date updatedAt;

上面的审计实体包含了 createAt、updateAt 两个日期类型字段, @CreatedDate、@LastModifiedDate 分别对应了各自的语义,还是比较容易理解的。

@Temporal 则用于声明日期类型对应的格式,如TIMESTAMP会对应 yyyy-MM-dd HH:mm:ss 的格式,而这个也会被体现到DDL中。

@MappedSuperClass 是必须的,目的是为了让子类定义的表能拥有继承的字段(列)

审计功能的“魔力”在于,添加了这些继承字段之后,对象在创建、更新时会自动刷新这几个字段,这些是由框架完成的,应用并不需要关心。

为了让审计功能生效,需要为AuditModel 添加 @EntityListeners(AuditingEntityListener.class) 声明,同时还应该为SpringBoot 应用声明启用审计:

  1. @EnableJpaAuditing

  2. @SpringBootApplication

  3. public class BootJpa {

  4. ...


D. 持久层

持久层基本是继承于 JpaRepository或CrudRepository的接口。 如下面的代码:

AuthorRepository

  1. @Repository

  2. public interface AuthorRepository extends JpaRepository<Author, Long> {

  3. }

BookRepository

  1. @Repository

  2. public interface BookRepository extends JpaRepository<Book, Long>{


  3. List<Book> findByType(String type, Pageable request);


  4. @Transactional

  5. @Modifying

  6. @Query("update Book b set b.favCount = b.favCount + ?2 where b.id = ?1")

  7. int incrFavCount(Long id, int fav);

  8. }

findByType 实现的是按照 类型(type) 进行查询,这个方法将会被自动转换为一个JPQL查询语句。

而且,SpringDataJPA 已经可以支持大部分常用场景,可以参考这里

incrFavCount 实现了收藏数的变更,除了使用 @Query 声明了一个update 语句之外,@Modify用于标记这是一个 “产生变更的查询” ,用于通知EntityManager及时清除缓存。

@Transactional 在这里是必须的,否则会提示 TransactionRequiredException 这样莫名其妙的错误。


E. Service 层

Service 的实现相对简单,仅仅是调用持久层实现数据操作。

  1. @Service

  2. public class BookService {


  3. @Autowired

  4. private BookRepository bookRepository;


  5. @Autowired

  6. private AuthorRepository authorRepository;



  7. /**

  8. * 创建作者信息

  9. *

  10. * @param name

  11. * @param hometown

  12. * @return

  13. */

  14. public Author createAuthor(String name, String hometown) {


  15. if (StringUtils.isEmpty(name)) {

  16. return null;

  17. }


  18. Author author = new Author();

  19. author.setName(name);

  20. author.setHometown(hometown);


  21. return authorRepository.save(author);

  22. }


  23. /**

  24. * 创建书籍信息

  25. *

  26. * @param author

  27. * @param type

  28. * @param title

  29. * @param description

  30. * @return

  31. */

  32. public Book createBook(Author author, String type, String title, String description) {


  33. if (StringUtils.isEmpty(type) || StringUtils.isEmpty(title) || author == null) {

  34. return null;

  35. }


  36. Book book = new Book();

  37. book.setType(type);

  38. book.setTitle(title);

  39. book.setDescription(description);


  40. book.setAuthor(author);

  41. return bookRepository.save(book);

  42. }



  43. /**

  44. * 更新书籍信息

  45. *

  46. * @param bookId

  47. * @param type

  48. * @param title

  49. * @param description

  50. * @return

  51. */

  52. @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, readOnly = false)

  53. public boolean updateBook(Long bookId, String type, String title, String description) {

  54. if (bookId == null || StringUtils.isEmpty(title)) {

  55. return false;

  56. }


  57. Book book = bookRepository.findOne(bookId);

  58. if (book == null) {

  59. return false;

  60. }


  61. book.setType(type);

  62. book.setTitle(title);

  63. book.setDescription(description);

  64. return bookRepository.save(book) != null;

  65. }


  66. /**

  67. * 删除书籍信息

  68. *

  69. * @param bookId

  70. * @return

  71. */

  72. public boolean deleteBook(Long bookId) {

  73. if (bookId == null) {

  74. return false;

  75. }



  76. Book book = bookRepository.findOne(bookId);

  77. if (book == null) {

  78. return false;

  79. }

  80. bookRepository.delete(book);

  81. return true;

  82. }


  83. /**

  84. * 根据编号查询

  85. *

  86. * @param bookId

  87. * @return

  88. */

  89. public Book getBook(Long bookId) {

  90. if (bookId == null) {

  91. return null;

  92. }

  93. return bookRepository.findOne(bookId);

  94. }


  95. /**

  96. * 增加收藏数

  97. *

  98. * @return

  99. */

  100. public boolean incrFav(Long bookId, int fav) {


  101. if (bookId == null || fav <= 0) {

  102. return false;

  103. }

  104. return bookRepository.incrFavCount(bookId, fav) > 0;

  105. }


  106. /**

  107. * 获取分类下书籍,按收藏数排序

  108. *

  109. * @param type

  110. * @return

  111. */

  112. public List<Book> listTopFav(String type, int max) {


  113. if (StringUtils.isEmpty(type) || max <= 0) {

  114. return Collections.emptyList();

  115. }


  116. // 按投票数倒序排序

  117. Sort sort = new Sort(Sort.Direction.DESC, "favCount");

  118. PageRequest request = new PageRequest(0, max, sort);


  119. return bookRepository.findByType(type, request);

  120. }

  121. }


四、高级操作

前面的部分已经完成了基础的CRUD操作,但在正式的项目中往往会需要一些定制做法,下面做几点介绍。

1. 自定义查询

使用 findByxxx 这样的方法映射已经可以满足大多数的场景,但如果是一些 "不确定" 的查询条件呢? 我们知道,JPA 定义了一套的 API 来帮助我们实现灵活的查询,通过EntityManager 可以实现各种灵活的组合查询。

那么在 Spring Data JPA 框架中该如何实现呢?

首先创建一个自定义查询的接口:

  1. public interface BookRepositoryCustom {

  2. public PageResult<Book> search(String type, String title, boolean hasFav, Pageable pageable);

  3. }

接下来让 BookRepository 继承于该接口:

  1. @Repository

  2. public interface BookRepository extends JpaRepository<Book, Long>, BookRepositoryCustom {

  3. ...

最终是 实现这个自定义接口,通过 AOP 的"魔法" ,框架会将我们的实现自动嫁接到接口实例上。

具体的实现如下:

  1. public class BookRepositoryImpl implements BookRepositoryCustom {


  2. private final EntityManager em;


  3. @Autowired

  4. public BookRepositoryImpl(JpaContext context) {

  5. this.em = context.getEntityManagerByManagedType(Book.class);

  6. }


  7. @Override

  8. public PageResult<Book> search(String type, String title, boolean hasFav, Pageable pageable) {

  9. CriteriaBuilder cb = em.getCriteriaBuilder();

  10. CriteriaQuery cq = cb.createQuery();


  11. Root<Book> root = cq.from(Book.class);


  12. List<Predicate> conds = new ArrayList<>();


  13. //按类型检索

  14. if (!StringUtils.isEmpty(type)) {

  15. conds.add(cb.equal(root.get("type").as(String.class

  16. ), type));

  17. }


  18. //标题模糊搜索

  19. if (!StringUtils.isEmpty(title)) {

  20. conds.add(cb.like(root.get("title").as(String.class

  21. ), "%" + title + "%"));

  22. }


  23. //必须被收藏过

  24. if (hasFav) {

  25. conds.add(cb.gt(root.get("favCount").as(Integer.class

  26. ), 0));

  27. }


  28. //count 数量

  29. cq.select(cb.count(root)).where(conds.toArray(new Predicate[0]));

  30. Long count = (Long) em.createQuery(cq).getSingleResult();


  31. if (count <= 0) {

  32. return PageResult.empty();

  33. }


  34. //list 列表

  35. cq.select(root).where(conds.toArray(new Predicate[0]));


  36. //获取排序

  37. List<Order> orders = toOrders(pageable, cb, root);


  38. if (!CollectionUtils.isEmpty(orders)) {

  39. cq.orderBy(orders);

  40. }



  41. TypedQuery<Book> typedQuery = em.createQuery(cq);


  42. //设置分页

  43. typedQuery.setFirstResult(pageable.getOffset());

  44. typedQuery.setMaxResults(pageable.getPageSize());


  45. List<Book> list = typedQuery.getResultList();


  46. return PageResult.of(count, list);


  47. }


  48. private List<Order> toOrders(Pageable pageable, CriteriaBuilder cb, Root<?> root) {


  49. List<Order> orders = new ArrayList<>();

  50. if (pageable.getSort() != null) {

  51. for (Sort.Order o : pageable.getSort()) {

  52. if (o.isAscending()) {

  53. orders.add(cb.asc(root.get(o.getProperty())));

  54. } else {

  55. orders.add(cb.desc(root.get(o.getProperty())));

  56. }

  57. }

  58. }


  59. return orders;

  60. }


  61. }


2. 聚合

聚合功能可以用 SQL 实现,但通过JPA 的 Criteria API 会更加简单。 与实现自定义查询的方法一样,也是通过EntityManager来完成操作:

  1. public List<Tuple> groupCount(){

  2. CriteriaBuilder cb = em.getCriteriaBuilder();

  3. CriteriaQuery cq = cb.createQuery();


  4. Root<Book> root = cq.from(Book.class);


  5. Path<String> typePath = root.get("type");


  6. //查询type/count(*)/sum(favCount)

  7. cq.select(cb.tuple(typePath,cb.count(root).alias("count"), cb.sum(root.get("favCount"))));

  8. //按type分组

  9. cq.groupBy(typePath);

  10. //按数量排序

  11. cq.orderBy(cb.desc(cb.literal("count")));


  12. //查询出元祖

  13. TypedQuery<Tuple> typedQuery = em.createQuery(cq);

  14. return typedQuery.getResultList();

  15. }

上面的代码中,会按书籍的分组统计数量,且按数量降序返回。 等价于下面的SQL:

select type, count(*) as count , sum(fav_count) from book group by type order by count;


3. 视图

视图的操作与表基本是相同的,只是视图一般是只读的(没有更新操作)。

执行下面的语句可以创建一个视图:

  1. create view v_author_book as

  2. select b.id, b.title, a.name as author_name,

  3. a.hometown as author_hometown, b.created_at

  4. from author a, book b

  5. where a.id = b.author_id;

在代码中 使用@Table来进行映射

  1. @Entity

  2. @Table(name = "v_author_book")

  3. public class AuthorBookView {


  4. @Id

  5. private Long id;

  6. private String title;


  7. @Column(name = "author_name")

  8. private String authorName;

  9. @Column(name = "author_hometown")

  10. private String authorHometown;


  11. @Column(name = "created_at")

  12. private Date createdAt;

创建一个相应的Repository:

  1. @Repository

  2. public interface AuthorBookViewRepository extends JpaRepository<AuthorBookView, Long> {


  3. }

这样就可以进行读写了。


4. 连接池

在生产环境中一般需要配置合适的连接池大小,以及超时参数等等。 这些需要通过对数据源(DataSource)进行配置来实现,DataSource也是一个抽象定义,默认情况下SpringBoot 1.x会使用Tomcat的连接池。

以Tomcat的连接池为例,配置如下:

  1. spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource


  2. # 初始连接数

  3. spring.datasource.tomcat.initial-size=15

  4. # 获取连接最大等待时长(ms)

  5. spring.datasource.tomcat.max-wait=20000

  6. # 最大连接数

  7. spring.datasource.tomcat.max-active=50

  8. # 最大空闲连接

  9. spring.datasource.tomcat.max-idle=20

  10. # 最小空闲连接

  11. spring.datasource.tomcat.min-idle=15

  12. # 是否自动提交事务

  13. spring.datasource.tomcat.default-auto-commit=true

从这里可以找到一些详尽的参数


5. 事务

SpringBoot 默认情况下会为我们开启事务的支持,引入 spring-starter-data-jpa 的组件将会默认使用 JpaTransactionManager 用于事务管理。

在业务代码中使用 @Transactional 可以声明一个事务,如下:

  1. @Transactional(propagation = Propagation.REQUIRED,

  2. isolation = Isolation.DEFAULT,

  3. readOnly = false,

  4. rollbackFor = Exception.class)

  5. public boolean updateBook(Long bookId, String type, String title, String description) {

  6. ...


为了演示事务的使用,上面的代码指定了几个关键属性,包括:

  • propagation 传递行为,指事务的创建或嵌套处理,默认为 REQUIRED

选项 描述
REQUIRED 使用已存在的事务,如果没有则创建一个。
MANDATORY 如果存在事务则加入,如果没有事务则报错。
REQUIRES_NEW 创建一个事务,如果已存在事务会将其挂起。
NOT_SUPPORTED 以非事务方式运行,如果当前存在事务,则将其挂起。
NEVER 以非事务方式运行,如果当前存在事务,则抛出异常。
NESTED 创建一个事务,如果已存在事务,新事务将嵌套执行。
  • isolation 隔离级别,默认值为DEFAULT

级别 描述
DEFAULT 默认值,使用底层数据库的默认隔离级别。大部分等于READ_COMMITTED
READ_UNCOMMITTED 未提交读,一个事务可以读取另一个事务修改但还没有提交的数据。不能防止脏读和不可重复读。
READ_COMMITTED 已提交读,一个事务只能读取另一个事务已经提交的数据。可以防止脏读,大多数情况下的推荐值。
REPEATABLE_READ 可重复读,一个事务在整个过程中可以多次重复执行某个查询,并且每次返回的记录都相同。可以防止脏读和不可重复读。
SERIALIZABLE 串行读,所有的事务依次逐个执行,这样事务之间就完全不可能产生干扰,可以防止脏读、不可重复读以及幻读。性能低。
  • readOnly
    指示当前事务是否为只读事务,默认为false

  • rollbackFor
    指示当捕获什么类型的异常时会进行回滚,默认情况下产生 RuntimeException 和 Error 都会进行回滚(受检异常除外)



参考文档

https://www.baeldung.com/spring-boot-tomcat-connection-pool

https://www.baeldung.com/transaction-configuration-with-jpa-and-spring

https://www.callicoder.com/spring-boot-jpa-hibernate-postgresql-restful-crud-api-example/

https://docs.spring.io/spring-data/jpa/docs/1.11.0.RELEASE/reference/html/#projections

https://www.cnblogs.com/yueshutong/p/9409295.html


小结

本篇文章描述了一个完整的 SpringBoot + JPA + PostGreSQL 开发案例,一些做法可供大家借鉴使用。 由于 JPA 帮我们简化许多了数据库的开发工作,使得我们在使用数据库时并不需要了解过多的数据库的特性。 因此,本文也适用于整合其他的关系型数据库。

前面也已经提到过,PostGreSQL由于其开源许可的开放性受到了云计算大T的青睐,相信未来前景可期。在接下来将会更多的关注该数据库的发展。

欢迎继续关注"美码师的补习系列-springboot篇" ,期待更多精彩内容^-^




相关文章推荐:

补习系列(18)-springboot H2 迷你数据库

补习系列(17)-springboot MongoDB 内嵌数据库

补习系列(16)-springboot MongoDB 应用技巧

补习系列(15)-springboot 分布式会话原理

补习系列(14)-springboot redis 读写秘技

补习系列(13)-springboot redis 与发布订阅

补习系列(12)-springboot 与邮件发送

补习系列(11)-springboot 文件上传原理

补习系列(10)-springboot 之配置读取





SQL oo JPA