將網(wǎng)站做成logo怎么做網(wǎng)店無貨源怎么做
現(xiàn)在我們來做一個(gè)簡(jiǎn)單的讀寫Mysql的項(xiàng)目
1,先新建一個(gè)項(xiàng)目,我們叫它“HelloJPA”并且添加依賴
2,引入以下依賴:
- Spring Boot DevTools (可選,但推薦,用于開發(fā)時(shí)熱部署)
- Lombok(可選,但推薦,用于減少樣板代碼)
- Spring Web(如果你需要?jiǎng)?chuàng)建一個(gè)Web應(yīng)用)
- Spring Data JPA(這是核心依賴,用于JPA功能)
- 數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序(例如MySQL Driver,如果你使用MySQL數(shù)據(jù)庫(kù))
在你的項(xiàng)目創(chuàng)建界面中,選擇以下依賴:
-
Developer Tools:
- Spring Boot DevTools
- Lombok
-
Web:
- Spring Web
-
SQL:
- Spring Data JPA
- MySQL Driver(或你使用的其他數(shù)據(jù)庫(kù)驅(qū)動(dòng))
這樣,你的項(xiàng)目將配置好進(jìn)行Spring Data JPA操作,并連接到你的數(shù)據(jù)庫(kù)。
3,我們現(xiàn)在右鍵點(diǎn)擊hellojpa文件夾下創(chuàng)建四個(gè)package:entity、repository、service、controller然后分別建一下4個(gè)類User、UserRepository、UserService、UserController
項(xiàng)目結(jié)構(gòu)如下
src/main/java
├── com
│ └── yuye
│ └── www
│ └── hellojpa
│ ├── controller
│ │ └── UserController.java
│ ├── entity
│ │ └── User.java
│ ├── repository
│ │ └── UserRepository.java
│ └── service
│ └── UserService.java
└── resources└── application.properties
1. entity
包
用途:用于定義應(yīng)用程序的核心業(yè)務(wù)對(duì)象,這些對(duì)象通常映射到數(shù)據(jù)庫(kù)表。
職責(zé):
- 定義Java對(duì)象,這些對(duì)象與數(shù)據(jù)庫(kù)中的表行相對(duì)應(yīng)。
- 使用JPA注解(例如
@Entity
,@Id
,@GeneratedValue
)來標(biāo)記這些類和它們的字段,從而指定它們?nèi)绾闻c數(shù)據(jù)庫(kù)交互。
2. repository
包
用途:用于定義數(shù)據(jù)訪問層,處理數(shù)據(jù)的CRUD(創(chuàng)建、讀取、更新、刪除)操作。
職責(zé):
- 繼承Spring Data JPA的
JpaRepository
接口,從而獲得基本的CRUD操作方法。 - 可以定義自定義查詢方法。
3. service
包
用途:用于定義業(yè)務(wù)邏輯層,封裝應(yīng)用程序的業(yè)務(wù)規(guī)則和操作。
職責(zé):
- 調(diào)用
repository
層的方法來處理數(shù)據(jù)。 - 執(zhí)行具體的業(yè)務(wù)邏輯,例如驗(yàn)證、數(shù)據(jù)轉(zhuǎn)換、復(fù)雜操作等。
4. controller
包
用途:用于定義表示層,處理來自客戶端的HTTP請(qǐng)求,并返回響應(yīng)。
職責(zé):
- 處理HTTP請(qǐng)求(例如GET, POST, PUT, DELETE)。
- 調(diào)用
service
層的方法來執(zhí)行業(yè)務(wù)邏輯。 - 返回處理結(jié)果給客戶端,通常以JSON格式。
總結(jié)
entity
:定義數(shù)據(jù)模型,映射數(shù)據(jù)庫(kù)表。repository
:數(shù)據(jù)訪問層,提供CRUD操作。service
:業(yè)務(wù)邏輯層,封裝業(yè)務(wù)規(guī)則和操作。controller
:表示層,處理HTTP請(qǐng)求和響應(yīng)。
?3,實(shí)現(xiàn)代碼
????????1. User
實(shí)體類
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所有數(shù)據(jù)唯一
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
可以配置很多東西,本次的配置主要是數(shù)據(jù)庫(kù)的連接
spring.application.name=HelloJPA# 連接到數(shù)據(jù)庫(kù)的URL
spring.datasource.url=jdbc:mysql://localhost:3306/userdata?useSSL=false&serverTimezone=UTC
# 連接數(shù)據(jù)庫(kù)的用戶名
spring.datasource.username=root
# 連接數(shù)據(jù)庫(kù)的密碼
spring.datasource.password=Qwerty123
# Hibernate 設(shè)置自動(dòng)更新數(shù)據(jù)庫(kù)模式
spring.jpa.hibernate.ddl-auto=update
# 在控制臺(tái)顯示SQL語句以便調(diào)試
spring.jpa.show-sql=true
# 指定Hibernate使用的SQL方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialectserver.port=8081
5,啟動(dòng)Mysql,創(chuàng)建數(shù)據(jù)庫(kù)和表格?
我們要預(yù)先在數(shù)據(jù)庫(kù)里面創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)、表格以及需要存儲(chǔ)的字段,然后啟動(dòng)數(shù)據(jù)庫(kù)后再去編譯項(xiàng)目,否則直接編譯項(xiàng)目會(huì)報(bào)錯(cuò)
如果你對(duì)數(shù)據(jù)庫(kù)的配置以及命令不熟悉,可以移步到我的前兩篇教程參考一下:
SpringBoot新手快速入門系列教程二:MySql5.7.44的免安裝版本下載和配置,以及簡(jiǎn)單的Mysql生存指令指南。-CSDN博客
SpringBoot新手快速入門系列教程三:Mysql基礎(chǔ)生存命令指南-CSDN博客
? ? ? ? 1,首先我們先啟動(dòng)mysql
mysqld --console
? ? ? ? 2,然后另外開啟一個(gè)命令行窗口,輸入密碼
mysql -u root -p
????????3,連接成功后,創(chuàng)建一個(gè)名為 UserData
的新數(shù)據(jù)庫(kù):??
CREATE DATABASE UserData;
????????4. 使用新創(chuàng)建的數(shù)據(jù)庫(kù)
USE UserData;
????????5. 創(chuàng)建 User
表
????????創(chuàng)建 User
表,并包含 id
和 name
字段:
CREATE TABLE User (id BIGINT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL
);
????????6. 驗(yàn)證表是否創(chuàng)建成功
SHOW TABLES;
7, IDEA連接數(shù)據(jù)庫(kù)
點(diǎn)擊創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)連接
右側(cè)展開后就是我們剛才創(chuàng)建的表格,右鍵點(diǎn)擊user
選擇editdata就可以看到我們剛才創(chuàng)建的name字段
另外一個(gè)實(shí)用的工具就是用在表格上方點(diǎn)擊右鍵、新建一個(gè)console就可以輸入sql命令了,輸入sql語句后用ctrl+enter組合按鈕,就可以執(zhí)行語句,下方result可以看執(zhí)行結(jié)果
7,運(yùn)行到這里我們先通過gradle的幾個(gè)腳本先編譯一下clean然后build
沒有報(bào)錯(cuò),就可以運(yùn)行一下項(xiàng)目看看
8,測(cè)試代碼
(1)打開命令行工具依次測(cè)試下面讀寫數(shù)據(jù)庫(kù)接口
curl -X POST http://localhost:8081/user/register -d "name=testuser"
(2)通過瀏覽器獲得剛才存入的name
curl http://localhost:8081/user/login?name=testuser
?