SpringBoot集成JPA全指南
一、前言
在 Java Web 開發(fā)中,數(shù)據(jù)庫訪問是繞不開的話題。
傳統(tǒng)方式使用 JDBC 編寫 SQL,維護(hù)困難、可讀性差。后來有了 MyBatis 這種半自動 ORM 框架,再到 JPA(Java Persistence API)這種全自動 ORM 規(guī)范,可以讓我們用面向?qū)ο蟮姆绞讲僮鲾?shù)據(jù)庫,而不必寫大量 SQL。
Spring Boot 對 JPA 提供了非常友好的自動化支持,幾乎可以“零配置”就完成數(shù)據(jù)庫操作。
二、JPA 簡介
JPA(Java Persistence API)并不是一個具體實(shí)現(xiàn),而是 Java 官方定義的 ORM 規(guī)范,它的常見實(shí)現(xiàn)有:
- Hibernate(最常用,Spring Boot 默認(rèn) JPA 實(shí)現(xiàn))
- EclipseLink
- OpenJPA
核心思想:
用 實(shí)體類(Entity)映射數(shù)據(jù)庫表,用 方法調(diào)用 代替手寫 SQL。
例如:
// 查詢所有用戶
List<User> users = userRepository.findAll();
// 根據(jù)用戶名查詢
User user = userRepository.findByUsername("Tom");
三、項(xiàng)目環(huán)境準(zhǔn)備
1. 新建 Spring Boot 項(xiàng)目
在 Spring Initializr 選擇:
Spring Boot 版本:3.x(或 2.7.x)
依賴:
- Spring Web
- Spring Data JPA
- MySQL Driver
生成后導(dǎo)入 IDE(IntelliJ IDEA / VSCode)。
2. Maven 依賴
如果是手動添加,pom.xml 配置如下:
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL 驅(qū)動 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 測試依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3. 配置數(shù)據(jù)庫連接
在 application.yml 中配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/jpa_demo?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update # 自動建表(create、update、validate、none)
show-sql: true # 控制臺打印 SQL
properties:
hibernate:
format_sql: true # 格式化 SQL 輸出
ddl-auto 參數(shù)說明:
create:每次啟動刪除舊表,創(chuàng)建新表update:如果表不存在則創(chuàng)建,如果有新字段則更新validate:驗(yàn)證表結(jié)構(gòu)和實(shí)體類是否匹配none:不做任何處理
四、編寫 JPA 樣例
1. 創(chuàng)建實(shí)體類
User.java
package com.example.jpademo.entity;
import jakarta.persistence.*;
import lombok.Data;
@Data
@Entity
@Table(name = "users") // 表名
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主鍵
private Long id;
@Column(nullable = false, unique = true, length = 50)
private String username;
@Column(nullable = false)
private String password;
}
2. 創(chuàng)建 Repository 接口
UserRepository.java
package com.example.jpademo.repository;
import com.example.jpademo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
// 按用戶名查找
User findByUsername(String username);
}
JpaRepository 已經(jīng)內(nèi)置了大量方法:save()、findAll()、findById()、deleteById() 等。
3. 創(chuàng)建 Service 層
UserService.java
package com.example.jpademo.service;
import com.example.jpademo.entity.User;
import com.example.jpademo.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User createUser(User user) {
return userRepository.save(user);
}
}
4. 創(chuàng)建 Controller
UserController.java
package com.example.jpademo.controller;
import com.example.jpademo.entity.User;
import com.example.jpademo.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> list() {
return userService.getAllUsers();
}
@PostMapping
public User add(@RequestBody User user) {
return userService.createUser(user);
}
}
五、運(yùn)行測試
啟動 Spring Boot 項(xiàng)目(IDEA Run)
使用 Postman 測試:
新增用戶
POST http://localhost:8080/users
Content-Type: application/json
{
"username": "Tom",
"password": "123456"
}
查詢所有用戶
GET http://localhost:8080/users
控制臺會輸出類似:
insert into users (password, username) values (?, ?) select u1_0.id, u1_0.password, u1_0.username from users u1_0
六、常見問題
為什么啟動時會自動建表?
因?yàn)?spring.jpa.hibernate.ddl-auto 設(shè)置了 update,Hibernate 會自動根據(jù)實(shí)體生成表結(jié)構(gòu)。
不想自動建表怎么辦?
把 ddl-auto 改成 none 或 validate,用手動 SQL 建表。
怎么寫復(fù)雜 SQL?
- 方法名查詢:
findByUsernameAndPassword - JPQL 查詢:
@Query("select u from User u where u.username = ?1") - 原生 SQL:
@Query(value = "select * from users where username = ?1", nativeQuery = true)
七、總結(jié)
Spring Boot 集成 JPA 最大的優(yōu)點(diǎn)就是:
- 幾乎零配置即可運(yùn)行
- 面向?qū)ο蟛僮鲾?shù)據(jù)庫,減少 SQL 編寫
- 內(nèi)置方法豐富,支持分頁、排序、條件查詢
- 復(fù)雜 SQL 也可以靈活編寫
但要注意:
- 適合中小型業(yè)務(wù),超復(fù)雜 SQL 可能 MyBatis 更高效
ddl-auto在生產(chǎn)環(huán)境建議設(shè)為none,防止誤刪表- 盡量用事務(wù)(
@Transactional)保證數(shù)據(jù)一致性
以上就是SpringBoot集成JPA全指南的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot集成JPA的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java中為什么要實(shí)現(xiàn)Serializable序列化
在Java編程中,Serializable序列化是一個常見的概念,它允許對象在網(wǎng)絡(luò)上傳輸或持久化到磁盤上,本文將深入探討為什么在Java中要實(shí)現(xiàn)Serializable序列化,并通過示例代碼來解釋其重要性2023-10-10
JAVA實(shí)戰(zhàn)練習(xí)之圖書管理系統(tǒng)實(shí)現(xiàn)流程
隨著網(wǎng)絡(luò)技術(shù)的高速發(fā)展,計(jì)算機(jī)應(yīng)用的普及,利用計(jì)算機(jī)對圖書館的日常工作進(jìn)行管理勢在必行,本篇文章手把手帶你用Java實(shí)現(xiàn)一個圖書管理系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2021-10-10
SpringBoot整合jnotify實(shí)現(xiàn)針對指定目錄及其(動態(tài))子目錄的監(jiān)聽的方法
本文介紹了JNotify這一Java庫在SpringBoot中的應(yīng)用,JNotify允許應(yīng)用程序監(jiān)聽文件系統(tǒng)事件,包括文件夾/文件的創(chuàng)建、刪除、修改和重命名,由于JNotify底層調(diào)用的關(guān)鍵部分是C語言開發(fā)的,所以在使用前需要在系統(tǒng)中加入相應(yīng)的動態(tài)庫2024-10-10
maven?導(dǎo)入resource?lib文件夾中的jar的幾種方法
本文主要介紹了maven?導(dǎo)入resource?lib文件夾中的jar的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-05-05
使用SpringData同時訪問MySQL和Neo4j數(shù)據(jù)庫
本文通過使用SpringData在SpringBoot中配置MySQL和Neo4j雙數(shù)據(jù)源,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-08-08
Java利用Redis實(shí)現(xiàn)高并發(fā)計(jì)數(shù)器的示例代碼
這篇文章主要介紹了Java利用Redis實(shí)現(xiàn)高并發(fā)計(jì)數(shù)器的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
java開發(fā)的工廠方法模式及抽象工廠驗(yàn)證示例
這篇文章主要為大家介紹了java開發(fā)中的工廠方法模式以及抽象工廠的驗(yàn)證示例,有需要的朋友可以借鑒參考下希望能夠有所幫助祝大家多多進(jìn)步2021-10-10

