現在我們來做一個簡單的讀寫Mysql的項目
1,先新建一個項目,我們叫它“HelloJPA”并且添加依賴
2,引入以下依賴:
- Spring Boot DevTools (可選,但推薦,用于開發時熱部署)
- Lombok(可選,但推薦,用于減少樣板代碼)
- Spring Web(如果你需要創建一個Web應用)
- Spring Data JPA(這是核心依賴,用于JPA功能)
- 數據庫驅動程序(例如MySQL Driver,如果你使用MySQL數據庫)
在你的項目創建界面中,選擇以下依賴:
-
Developer Tools:
- Spring Boot DevTools
- Lombok
-
Web:
- Spring Web
-
SQL:
- Spring Data JPA
- MySQL Driver(或你使用的其他數據庫驅動)
這樣,你的項目將配置好進行Spring Data JPA操作,并連接到你的數據庫。
3,我們現在右鍵點擊hellojpa文件夾下創建四個package:entity、repository、service、controller然后分別建一下4個類User、UserRepository、UserService、UserController
項目結構如下
src/main/java
├── com
│ └── yuye
│ └── www
│ └── hellojpa
│ ├── controller
│ │ └── UserController.java
│ ├── entity
│ │ └── User.java
│ ├── repository
│ │ └── UserRepository.java
│ └── service
│ └── UserService.java
└── resources└── application.properties
1. entity
包
用途:用于定義應用程序的核心業務對象,這些對象通常映射到數據庫表。
職責:
- 定義Java對象,這些對象與數據庫中的表行相對應。
- 使用JPA注解(例如
@Entity
,@Id
,@GeneratedValue
)來標記這些類和它們的字段,從而指定它們如何與數據庫交互。
2. repository
包
用途:用于定義數據訪問層,處理數據的CRUD(創建、讀取、更新、刪除)操作。
職責:
- 繼承Spring Data JPA的
JpaRepository
接口,從而獲得基本的CRUD操作方法。 - 可以定義自定義查詢方法。
3. service
包
用途:用于定義業務邏輯層,封裝應用程序的業務規則和操作。
職責:
- 調用
repository
層的方法來處理數據。 - 執行具體的業務邏輯,例如驗證、數據轉換、復雜操作等。
4. controller
包
用途:用于定義表示層,處理來自客戶端的HTTP請求,并返回響應。
職責:
- 處理HTTP請求(例如GET, POST, PUT, DELETE)。
- 調用
service
層的方法來執行業務邏輯。 - 返回處理結果給客戶端,通常以JSON格式。
總結
entity
:定義數據模型,映射數據庫表。repository
:數據訪問層,提供CRUD操作。service
:業務邏輯層,封裝業務規則和操作。controller
:表示層,處理HTTP請求和響應。
?3,實現代碼
????????1. User
實體類
package com.yuye.www.hellojpa.entity;import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;/*** The User entity class represents a user in the system.* It is mapped to a table in the database using JPA annotations.*/
@Entity
@Table(name = "user", uniqueConstraints = {@UniqueConstraint(columnNames = "name")})//保證user所有數據唯一
public class User {// The unique identifier for each user, generated automatically.@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;// The name of the user.private String name;// Getters and setters for the fields.public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}
????????2. UserRepository
接口
package com.yuye.www.hellojpa.repository;import com.yuye.www.hellojpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;/*** The UserRepository interface provides CRUD operations for User entities.* It extends JpaRepository to leverage Spring Data JPA functionalities.*/
public interface UserRepository extends JpaRepository<User, Long> {/*** Finds a user by their name.* * @param name the name of the user to find* @return the User entity if found, otherwise null*/User findByName(String name);
}
????????3. UserService
類
package com.yuye.www.hellojpa.service;import com.yuye.www.hellojpa.entity.User;
import com.yuye.www.hellojpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** The UserService class provides business logic for user registration and login.*/
@Service
public class UserService {@Autowiredprivate UserRepository userRepository;/*** Registers a new user with the given name.* * @param name the name of the user to register*/public void register(String name) {User user = new User();user.setName(name);userRepository.save(user);}/*** Checks if a user with the given name exists.* * @param name the name of the user to check* @return true if the user exists, otherwise false*/public boolean login(String name) {User user = userRepository.findByName(name);return user != null;}
}
????????4. UserController
類
package com.yuye.www.hellojpa.controller;import com.yuye.www.hellojpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;/*** The UserController class handles HTTP requests for user registration and login.*/
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;/*** Registers a new user.* * @param name the name of the user to register* @return a JSON string indicating the result of the operation*/@PostMapping("/register")public String register(@RequestParam String name) {userService.register(name);return "{\"status\":\"success\"}";}/*** Checks if a user with the given name exists.* * @param name the name of the user to check* @return a JSON string indicating the result of the operation*/@GetMapping("/login")public String login(@RequestParam String name) {boolean exists = userService.login(name);if (exists) {return "{\"status\":\"exists\"}";} else {return "{\"status\":\"no exists\"}";}}
}
??4,application.properties
配置
?application.properties
可以配置很多東西,本次的配置主要是數據庫的連接
spring.application.name=HelloJPA# 連接到數據庫的URL
spring.datasource.url=jdbc:mysql://localhost:3306/userdata?useSSL=false&serverTimezone=UTC
# 連接數據庫的用戶名
spring.datasource.username=root
# 連接數據庫的密碼
spring.datasource.password=Qwerty123
# Hibernate 設置自動更新數據庫模式
spring.jpa.hibernate.ddl-auto=update
# 在控制臺顯示SQL語句以便調試
spring.jpa.show-sql=true
# 指定Hibernate使用的SQL方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialectserver.port=8081
5,啟動Mysql,創建數據庫和表格?
我們要預先在數據庫里面創建一個數據庫、表格以及需要存儲的字段,然后啟動數據庫后再去編譯項目,否則直接編譯項目會報錯
如果你對數據庫的配置以及命令不熟悉,可以移步到我的前兩篇教程參考一下:
SpringBoot新手快速入門系列教程二:MySql5.7.44的免安裝版本下載和配置,以及簡單的Mysql生存指令指南。-CSDN博客
SpringBoot新手快速入門系列教程三:Mysql基礎生存命令指南-CSDN博客
? ? ? ? 1,首先我們先啟動mysql
mysqld --console
? ? ? ? 2,然后另外開啟一個命令行窗口,輸入密碼
mysql -u root -p
????????3,連接成功后,創建一個名為 UserData
的新數據庫:??
CREATE DATABASE UserData;
????????4. 使用新創建的數據庫
USE UserData;
????????5. 創建 User
表
????????創建 User
表,并包含 id
和 name
字段:
CREATE TABLE User (id BIGINT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL
);
????????6. 驗證表是否創建成功
SHOW TABLES;
7, IDEA連接數據庫
點擊創建一個數據庫連接
右側展開后就是我們剛才創建的表格,右鍵點擊user
選擇editdata就可以看到我們剛才創建的name字段
另外一個實用的工具就是用在表格上方點擊右鍵、新建一個console就可以輸入sql命令了,輸入sql語句后用ctrl+enter組合按鈕,就可以執行語句,下方result可以看執行結果
7,運行到這里我們先通過gradle的幾個腳本先編譯一下clean然后build
沒有報錯,就可以運行一下項目看看
8,測試代碼
(1)打開命令行工具依次測試下面讀寫數據庫接口
curl -X POST http://localhost:8081/user/register -d "name=testuser"
(2)通過瀏覽器獲得剛才存入的name
curl http://localhost:8081/user/login?name=testuser
?