欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot集成JPA全指南

 更新時間:2025年08月17日 10:16:21   作者:柯南二號  
在Java Web開發(fā)中,數(shù)據(jù)庫訪問是繞不開的話題,傳統(tǒng)方式使用JDBC編寫SQL,維護(hù)困難、可讀性差,后來有了MyBatis這種半自動ORM框架,再到JPA這種全自動ORM規(guī)范,SpringBoot對JPA提供了非常友好的自動化支持,本文給大家介紹了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 改成 nonevalidate,用手動 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)文章

最新評論