四平网站建设怎么选,加盟招商推广网站,设计自己的名字图画,个人开小公司的流程现在我们来做一个简单的读写Mysql的项目
1#xff0c;先新建一个项目#xff0c;我们叫它“HelloJPA”并且添加依赖 2#xff0c;引入以下依赖#xff1a;
Spring Boot DevTools (可选#xff0c;但推荐#xff0c;用于开发时热部署)Lombok#xff08;可选#xff0c… 现在我们来做一个简单的读写Mysql的项目
1先新建一个项目我们叫它“HelloJPA”并且添加依赖 2引入以下依赖
Spring Boot DevTools (可选但推荐用于开发时热部署)Lombok可选但推荐用于减少样板代码Spring Web如果你需要创建一个Web应用Spring Data JPA这是核心依赖用于JPA功能数据库驱动程序例如MySQL Driver如果你使用MySQL数据库
在你的项目创建界面中选择以下依赖 Developer Tools: Spring Boot DevToolsLombok Web: Spring Web SQL: Spring Data JPAMySQL Driver或你使用的其他数据库驱动
这样你的项目将配置好进行Spring Data JPA操作并连接到你的数据库。 3我们现在右键点击hellojpa文件夹下创建四个packageentity、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.properties1. 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.IdGeneratedValue(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 JpaRepositoryUser, 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\};}}
}4application.properties 配置 application.properties 可以配置很多东西本次的配置主要是数据库的连接
spring.application.nameHelloJPA# 连接到数据库的URL
spring.datasource.urljdbc:mysql://localhost:3306/userdata?useSSLfalseserverTimezoneUTC
# 连接数据库的用户名
spring.datasource.usernameroot
# 连接数据库的密码
spring.datasource.passwordQwerty123
# Hibernate 设置自动更新数据库模式
spring.jpa.hibernate.ddl-autoupdate
# 在控制台显示SQL语句以便调试
spring.jpa.show-sqltrue
# 指定Hibernate使用的SQL方言
spring.jpa.properties.hibernate.dialectorg.hibernate.dialect.MySQLDialectserver.port8081
5启动Mysql创建数据库和表格
我们要预先在数据库里面创建一个数据库、表格以及需要存储的字段然后启动数据库后再去编译项目否则直接编译项目会报错
如果你对数据库的配置以及命令不熟悉可以移步到我的前两篇教程参考一下
SpringBoot新手快速入门系列教程二MySql5.7.44的免安装版本下载和配置以及简单的Mysql生存指令指南。-CSDN博客
SpringBoot新手快速入门系列教程三Mysql基础生存命令指南-CSDN博客 1首先我们先启动mysql
mysqld --console 2然后另外开启一个命令行窗口输入密码
mysql -u root -p3连接成功后创建一个名为 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语句后用ctrlenter组合按钮就可以执行语句下方result可以看执行结果 7运行到这里我们先通过gradle的几个脚本先编译一下clean然后build 没有报错就可以运行一下项目看看 8测试代码
1打开命令行工具依次测试下面读写数据库接口
curl -X POST http://localhost:8081/user/register -d nametestuser 2通过浏览器获得刚才存入的name
curl http://localhost:8081/user/login?nametestuser