Spring?Boot?ORM?框架JPA使用與連接池?Hikari詳解
1.Spring Boot ORM 框架JPA使用與連接池 Hikari
1.數(shù)據(jù)庫方面我們選用 Mysql Spring Boot 提供了直接使用 JDBC 的方式連接數(shù)據(jù)庫,畢竟使用 JDBC 并不是很方便,需要我們自己寫更多的代碼才能使用,一般而言在 Spring Boot 中我們常用的 ORM 框架有 JPA 和 Mybaties ,本篇文章我們要介紹的就是 JPA 的使用姿勢。
說道使用 ORM 框架,就不得不順便聊一下連接池,市面上很多成熟的數(shù)據(jù)庫連接池,如 C3P0 、 Tomcat 連接池、 BoneCP 等等很多產(chǎn)品,但是我們?yōu)槭裁匆榻B Hikari ?這個要從 BoneCP 說起。
因為,傳說中 BoneCP 在快速這個特點上做到了極致,官方數(shù)據(jù)是C3P0等的25倍左右。不相信?其實我也不怎么信??墒牵袌D有真相啊,傳說圖片來源于官網(wǎng),然而筆者在官網(wǎng)并沒有找到,大家看一下:

看起來是不是完全吊打,但是當 HikariCP 橫空出世以后,這個局面就被完全改寫了, BoneCP 被 HikariCP 完全吊打,看了一下 BoneCP Github 上面的版本更新,發(fā)現(xiàn)在2013年10月23日以后就再也沒有更新過了,包括在倉庫介紹上面都寫著建議大家使用 HikariCP ,看來作者已經(jīng)完全心灰意冷了。

Hikari 這個詞來源于日文,是“光”的意思,估計作者的意思是這個連接池將會和光一樣快,不知道作者是不是日本人。
HikariCP 的口號是快速,簡單,可靠。不知道是否真的如它自己宣傳的一樣,官方又提供了一張圖。

2. JPA 介紹
JPA (Java Persistence API) 是 Sun 官方提出的 Java 持久化規(guī)范。它為 Java 開發(fā)人員提供了一種對象/關(guān)聯(lián)映射工具來管理 Java 應(yīng)用中的關(guān)系數(shù)據(jù)。它的出現(xiàn)主要是為了簡化現(xiàn)有的持久化開發(fā)工作和整合 ORM 技術(shù),結(jié)束現(xiàn)在 Hibernate,TopLink,JDO 等 ORM 框架各自為營的局面。
值得注意的是,JPA 是在充分吸收了現(xiàn)有 Hibernate,TopLink,JDO 等 ORM 框架的基礎(chǔ)上發(fā)展而來的,具有易于使用,伸縮性強等優(yōu)點。從目前的開發(fā)社區(qū)的反應(yīng)上看, JPA 受到了極大的支持和贊揚,其中就包括了 Spring 與 EJB3. 0的開發(fā)團隊。
注意: JPA 是一套規(guī)范,不是一套產(chǎn)品,那么像 Hibernate,TopLink,JDO 他們是一套產(chǎn)品,如果說這些產(chǎn)品實現(xiàn)了這個 JPA 規(guī)范,那么我們就可以叫他們?yōu)?JPA 的實現(xiàn)產(chǎn)品。
Spring Boot JPA 是 Spring 基于 ORM 框架、 JPA 規(guī)范的基礎(chǔ)上封裝的一套 JPA 應(yīng)用框架,可使開發(fā)者用極簡的代碼即可實現(xiàn)對數(shù)據(jù)的訪問和操作。它提供了包括增刪改查等在內(nèi)的常用功能,且易于擴展!學習并使用 Spring Data JPA 可以極大提高開發(fā)效率!
Spring Boot JPA 讓我們解脫了 DAO 層的操作,基本上所有 CRUD 都可以依賴于它來實現(xiàn)。
Spring Boot JPA 幫我們定義了很多自定義的簡單查詢,并且可以根據(jù)方法名來自動生成 SQL ,主要的語法是 findXXBy , readAXXBy , queryXXBy , countXXBy , getXXBy 后面跟屬性名稱:
public interface UserRepository extends JpaRepository<UserModel, Long> {
UserModel getByIdIs(Long id);
UserModel findByNickName(String nickName);
int countByAge(int age);
List<UserModel> findByNickNameLike(String nickName);
}具體的關(guān)鍵字,使用方法和生產(chǎn)成SQL如下表所示:
Keyword Sample JPQL snippet And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2 Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2 Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = 1? Between findByStartDateBetween … where x.startDate between 1? and ?2 LessThan findByAgeLessThan … where x.age < ?1 LessThanEqual findByAgeLessThanEqual … where x.age <= ?1 GreaterThan findByAgeGreaterThan … where x.age > ?1 GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1 After findByStartDateAfter … where x.startDate > ?1 Before findByStartDateBefore … where x.startDate < ?1 IsNull findByAgeIsNull … where x.age is null IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null Like findByFirstnameLike … where x.firstname like ?1 NotLike findByFirstnameNotLike … where x.firstname not like ?1 StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %) EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %) Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %) OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc Not findByLastnameNot … where x.lastname <> ?1 In findByAgeIn(Collection ages) … where x.age in ?1 NotIn findByAgeNotIn(Collection age) … where x.age not in ?1 True findByActiveTrue() … where x.active = true False findByActiveFalse() … where x.active = false IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)
3. 工程實戰(zhàn)
這里我們創(chuàng)建工程 spring-boot-jpa-hikari 。
3.1 工程依賴 pom.xml
代碼清單:spring-boot-jpa-hikari/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>spring-boot-jpa-hikari</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-jpa-hikari</name>
<description>spring-boot-jpa-hikari</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>mysql-connector-java:mysql連接驅(qū)動spring-boot-starter-data-jpa:jpa相關(guān)的依賴包,這個包里包含了很多內(nèi)容,包括我們使用的連接池 HikariCP ,從 Spring Boot 2.x 開始, Spring Boot 默認的連接池更換成為 HikariCP ,在當前的 Spring Boot 2.1.8 RELEASE 版本中,所使用的 HikariCP 版本為 3.2.0 ,如圖:

3.2 配置文件 application.yml
代碼清單:spring-boot-jpa-hikari/src/main/resources/application.yml
server:
port: 8080
spring:
application:
name: spring-boot-jpa-hikari
jpa:
database: mysql
show-sql: true
generate-ddl: true
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
hibernate:
ddl-auto: update
datasource:
url: jdbc:mysql://192.168.0.128:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
auto-commit: true
minimum-idle: 2
idle-timeout: 60000
connection-timeout: 30000
max-lifetime: 1800000
pool-name: DatebookHikariCP
maximum-pool-size: 5注意:
有關(guān) JPA 的配置有一點需要的, spring.jpa.hibernate.ddl-auto ,這個屬性需謹慎配置,它的幾個值的含義對數(shù)據(jù)庫來講都是高危操作,筆者這里方便起見配置了 update ,各位讀者請根據(jù)具體使用場景配置。
create :每次加載hibernate時都會刪除上一次的生成的表,然后根據(jù)你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執(zhí)行,這就是導致數(shù)據(jù)庫表數(shù)據(jù)丟失的一個重要原因。create-drop :每次加載hibernate時根據(jù)model類生成表,但是sessionFactory一關(guān)閉,表就自動刪除。update :最常用的屬性,第一次加載hibernate時根據(jù)model類會自動建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫),以后加載hibernate時根據(jù) model類自動更新表結(jié)構(gòu),即使表結(jié)構(gòu)改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務(wù)器后,表結(jié)構(gòu)是不會被馬上建立起來的,是要等 應(yīng)用第一次運行起來后才會。validate :每次加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會和數(shù)據(jù)庫中的表進行比較,不會創(chuàng)建新表,但是會插入新值。none :不做任何操作有關(guān) HikariCP 更多的配置可以參考源碼類 com.zaxxer.hikari.HikariConfig ,筆者這里僅簡單配置了自動提交、超時時間、最大最小連接數(shù)等配置。
3.3 映射實體類 UserModel.java
代碼清單:spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/model/UserModel.java
@Entity
@Data
@Table(name = "user")
public class UserModel {
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
@Column(name ="ID",nullable=false,length=36)
private String id;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private int age;
}unique : 唯一約束
主鍵生成策略為uuid
3.4 資源類 UserRepository.java
代碼清單:spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/repository/UserRepository.java
public interface UserRepository extends JpaRepository<UserModel, Long> {
UserModel getByIdIs(Long id);
UserModel findByNickName(String nickName);
int countByAge(int age);
List<UserModel> findByNickNameLike(String nickName);
}3.5 接口測試類 UserController.java
代碼清單:spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/controller/UserController.java
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
/**
* 查詢用戶列表
* @return
*/
@GetMapping("/user")
public List<UserModel> user() {
return userRepository.findAll(Sort.by("id").descending());
}
/**
* 新增或更新用戶信息
* @param user
* @return
*/
@PostMapping("/user")
public UserModel user(UserModel user) {
return userRepository.save(user);
}
/**
* 根據(jù)id刪除用戶
* @param id
* @return
*/
@DeleteMapping("/user")
public String deleteUserById(Long id) {
userRepository.deleteById(id);
return "success";
}
}4. 測試
測試我們借助工具 PostMan ,啟動工程,首先我們新增一個用戶信息,如圖:


我們執(zhí)行查詢操作,如圖:

執(zhí)行刪除操作,如圖:

至此,測試完成。
到此這篇關(guān)于Spring Boot ORM 框架 JPA 與連接池 Hikari的文章就介紹到這了,更多相關(guān)Spring Boot ORM 框架 JPA內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?RestTemplate遠程調(diào)用過程
這篇文章主要介紹了Spring?RestTemplate遠程調(diào)用過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
解決Spring Cloud feign GET請求無法用實體傳參的問題
這篇文章主要介紹了解決Spring Cloud feign GET請求無法用實體傳參的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
詳解Spring-boot中讀取config配置文件的兩種方式
這篇文章主要介紹了詳解Spring-boot中讀取config配置文件的兩種方式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
關(guān)于weblogic部署Java項目的包沖突問題的解決
這篇文章主要介紹了關(guān)于weblogic部署Java項目的包沖突問題的解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-01-01
SpringBoot條件注解之@ConditionalOnClass等注解的使用場景分析
文章詳細介紹了SpringBoot中條件注解的體系,包括基本概念、@ConditionalOnClass等常用注解的工作原理和使用場景,文章還探討了條件注解的組合使用、實戰(zhàn)應(yīng)用以及最佳實踐,幫助開發(fā)者更好地理解和應(yīng)用條件注解,實現(xiàn)更靈活和智能的應(yīng)用配置,感興趣的朋友一起看看吧2025-03-03
idea設(shè)置在包里面在創(chuàng)建一個包方式
這篇文章主要介紹了idea設(shè)置在包里面在創(chuàng)建一個包方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
springboot2.0配置連接池(hikari、druid)的方法
springboot 2.0 默認連接池就是Hikari了,直接在配置文件中輸入配置就可以了,本文通過實例代碼給大家介紹了springboot2.0配置連接池(hikari、druid)的方法,感興趣的朋友一起看看吧2021-12-12

