SpringBoot 中JPA集成PostgreSql(詳細說明)

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.properties文件中添加如下:

#數據庫基本信息配置
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/yourdatabase
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
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

注意:

  • yourdatabase,yourusername,yourpassword等信息是否配置正確。

  • spring.jpa.hibernate.ddl-auto 指定爲 update,這樣框架會自動幫我們創建或更新表結構

三、定義Entity

package com.book.entity;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "bookshelf")
public class BookshelfItem {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name = "bookName",nullable = false)
    private String bookName;
    @Column(name = "describe")
    private String describe;
    @Column(name = "detail")
    private String detail;

    public  String  ToString()
    {
        return bookName + "-" + describe;
    }

}

注意:

  • 如果你的數據庫中有自己創建的嵌套schema,要在Table屬性中進行寫明@Table(name = “bookshelf”,schema = “yourschema”)
  • bookName這樣的寫法會導致如果數據庫沒有這個數據元,則會創建成book_name

四、定義repository

package com.book.repository;

import com.book.entity.BookshelfItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface BookshelfRepository extends JpaRepository<BookshelfItem,Integer> {
    @Query(value = "select * from bookshelf",nativeQuery = true)
    List<BookshelfItem> GetAllBookData();
    @Query(value = "select * from bookshelf where book_name = :bookName",nativeQuery = true)
    List<BookshelfItem> GetBooksByName(@Param("bookName") String bookName);
}

注意:

  • 如果**@Query中有*號**,要在尾部加上nativeQuery = true

五、定義service

package com.book.service;

import com.book.entity.BookshelfItem;
import com.book.repository.BookshelfRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookshelfService {
    @Autowired
    private BookshelfRepository bookshelfRepository;
    public List<BookshelfItem> GetAll()
    {
        return  bookshelfRepository.GetAllBookData();
    }
    public List<BookshelfItem> GetNyBookname(String bookName)
    {
        return  bookshelfRepository.GetBooksByName(bookName);
    }

}

單元測試

package com.book;

import com.book.entity.BookshelfItem;
import com.book.service.BookshelfService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BookApplicationTests {
    @Autowired
    BookshelfService bookshelfService;
    @Test
    public void contextLoads() {

        System.out.println("Get book All");
        List<BookshelfItem> temp = bookshelfService.GetAll();
        for (int i = 0; i < temp.size(); i++) {
            BookshelfItem item = temp.get(i);
            System.out.println(item.toString());
        }
        System.out.println("Get book by Name");
        temp = bookshelfService.GetNyBookname("boo1");
        for (int i = 0; i < temp.size(); i++) {
            BookshelfItem item = temp.get(i);
            System.out.println(item.toString());
        }
    }

}

本人測試結果如下(數據爲我自己在數據庫中添加的兩條數據):

2019-10-08 17:01:07.646  INFO 4276 --- [           main] com.book.BookApplicationTests            : Started BookApplicationTests in 4.878 seconds (JVM running for 5.5)
Get book All
Hibernate: select * from bookshelf
BookshelfItem(id=1, bookName=boo1, describe=sdfsad, detail=sdfgdg)
BookshelfItem(id=2, bookName=boo2, describe=jkjkjk, detail=aaaaaa)
Get book by Name
Hibernate: select * from bookshelf where book_name = ?
BookshelfItem(id=1, bookName=boo1, describe=sdfsad, detail=sdfgdg)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.406 s - in com.book.BookApplicationTests
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章