Spring Boot+Vue3搭建CRUDDemo
一、项目选择与初始化一个典型的 CRUD Demo 项目是个人博客系统或仓库管理系统它们功能明确、技术栈成熟适合作为仓库初始内容。这里以Spring Boot Vue3 前后端分离博客系统为例进行说明 。1. 后端项目初始化 (Spring Boot)使用 Spring Initializr 快速生成项目骨架。# 使用 curl 命令生成项目 (示例) curl https://start.spring.io/starter.zip \ d typemaven-project \ -d languagejava \ d bootVersion3.2.5 \ d baseDirblog-backend \ d groupIdcom.example \ -d artifactIdblog \ -d nameblog \ d descriptionSpring Boot Blog Backend \ -d packageNamecom.example.blog \ -d packagingjar \ d javaVersion17 \ d dependenciesweb,data-jpa,mysql,validation,security \ o blog-backend.zip解压后得到标准的 Maven 项目结构 。2. 前端项目初始化 (Vue3)使用 Vite 快速创建 Vue3 项目。# 使用 npm 创建项目 npm create vuelatest blog-frontend # 根据提示选择配置例如加入 Router, Pinia 等 cd blog-frontend npm install npm run dev二、核心 CRUD 功能实现以文章管理为例1. 后端实体与 Repository (Spring Data JPA)// src/main/java/com/example/blog/entity/Article.java package com.example.blog.entity; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDateTime; Entity Data Table(name articles) public class Article { Id GeneratedValue(strategy GenerationType.IDENTITY) private Long id; private String title; Lob private String content; private String author; private LocalDateTime createTime; private LocalDateTime updateTime; }// src/main/java/com/example/blog/repository/ArticleRepository.java package com.example.blog.repository; import com.example.blog.entity.Article; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; Repository public interface ArticleRepository extends JpaRepositoryArticle, Long { }2. 后端 Service 与 Controller (RESTful API)// src/main/java/com/example/blog/service/ArticleService.java package com.example.blog.service; import com.example.blog.entity.Article; import com.example.blog.repository.ArticleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; Service public class ArticleService { Autowired private ArticleRepository articleRepository; public ListArticle findAll() { return articleRepository.findAll(); } public OptionalArticle findById(Long id) { return articleRepository.findById(id); } public Article save(Article article) { if (article.getId() null) { article.setCreateTime(LocalDateTime.now()); } article.setUpdateTime(LocalDateTime.now()); return articleRepository.save(article); } public void deleteById(Long id) { articleRepository.deleteById(id); } }// src/main/java/com/example/blog/controller/ArticleController.java package com.example.blog.controller; import com.example.blog.entity.Article; import com.example.blog.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; RestController RequestMapping(/api/articles) public class ArticleController { Autowired private ArticleService articleService; GetMapping public ResponseEntityListArticle getAllArticles() { return ResponseEntity.ok(articleService.findAll()); } GetMapping(/{id}) public ResponseEntityArticle getArticleById(PathVariable Long id) { OptionalArticle article articleService.findById(id); return article.map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } PostMapping public ResponseEntityArticle createArticle(RequestBody Article article) { return ResponseEntity.ok(articleService.save(article)); } PutMapping(/{id}) public ResponseEntityArticle updateArticle(PathVariable Long id, RequestBody Article article) { if (!articleService.findById(id).isPresent()) { return ResponseEntity.notFound().build(); } article.setId(id); return ResponseEntity.ok(articleService.save(article)); } DeleteMapping(/{id}) public ResponseEntityVoid deleteArticle(PathVariable Long id) { if (!articleService.findById(id).isPresent()) { return ResponseEntity.notFound().build(); } articleService.deleteById(id); return ResponseEntity.noContent().build(); } }3. 前端页面与 API 调用 (Vue3 Composition API Axios)!-- src/views/ArticleList.vue -- template div h1文章列表/h1 button clickshowCreateForm新建文章/button ul li v-forarticle in articles :keyarticle.id {{ article.title }} - {{ article.author }} button clickeditArticle(article)编辑/button button clickdeleteArticle(article.id)删除/button /li /ul !-- 创建/编辑表单 -- div v-ifshowForm h2{{ formTitle }}/h2 form submit.preventsubmitForm input v-modelcurrentArticle.title placeholder标题 required / textarea v-modelcurrentArticle.content placeholder内容 required/textarea input v-modelcurrentArticle.author placeholder作者 required / button typesubmit提交/button button typebutton clickcancelForm取消/button /form /div /div /template script setup import { ref, onMounted } from vue import axios from axios const API_BASE http://localhost:8080/api/articles const articles ref([]) const showForm ref(false) const formTitle ref() const currentArticle ref({ id: null, title: , content: , author: }) // 获取文章列表 const fetchArticles async () { try { const response await axios.get(API_BASE) articles.value response.data } catch (error) { console.error(获取文章失败:, error) } } // 创建文章 const createArticle async (article) { await axios.post(API_BASE, article) fetchArticles() } // 更新文章 const updateArticle async (id, article) { await axios.put(${API_BASE}/${id}, article) fetchArticles() } // 删除文章 const deleteArticle async (id) { if (confirm(确定删除吗)) { await axios.delete(${API_BASE}/${id}) fetchArticles() } } // 表单操作 const showCreateForm () { currentArticle.value { id: null, title: , content: , author: } formTitle.value 创建文章 showForm.value true } const editArticle (article) { currentArticle.value { ...article } formTitle.value 编辑文章 showForm.value true } const submitForm () { if (currentArticle.value.id) { updateArticle(currentArticle.value.id, currentArticle.value) } else { createArticle(currentArticle.value) } cancelForm() } const cancelForm () { showForm.value false } onMounted(() { fetchArticles() }) /script三、数据库配置与连接1. 后端application.properties配置# src/main/resources/application.properties spring.application.nameblog-backend server.port8080 # 数据库配置 (MySQL示例) spring.datasource.urljdbc:mysql://localhost:3306/blog_db?useSSLfalseserverTimezoneUTCcharacterEncodingutf8 spring.datasource.usernameroot spring.datasource.passwordyourpassword spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver # JPA 配置 spring.jpa.hibernate.ddl-autoupdate spring.jpa.show-sqltrue spring.jpa.properties.hibernate.dialectorg.hibernate.dialect.MySQL8Dialect spring.jpa.properties.hibernate.format_sqltrue2. 初始化 SQL 脚本 (可选)-- 创建数据库CREATE DATABASE IF NOT EXISTS blog_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; USE blog_db; -- 创建文章表 (JPA的ddl-autoupdate通常会自动生成) CREATE TABLE IF NOT EXISTS articles ( id BIGINT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255) NOT NULL, content TEXT, author VARCHAR(100), create_time DATETIME, update_time DATETIME );四、项目结构与关键文件一个完整的 CRUD Demo 仓库应包含以下核心结构blog-demo/ ├── blog-backend/ # Spring Boot 后端 │ ├── src/ │ │ ├── main/ │ │ │ ├── java/com/example/blog/ │ │ │ │ ├── entity/ # 实体类 (如 Article.java) │ │ │ │ ├── repository/ # 数据访问层 (如 ArticleRepository.java) │ │ │ │ ├── service/ # 业务逻辑层 (如 ArticleService.java) │ │ │ │ ├── controller/ #控制层 (如 ArticleController.java) │ │ │ │ └── BlogApplication.java # 主启动类 │ │ │ └── resources/ │ │ │ ├── application.properties # 配置文件 │ │ │ └── static/ # 静态资源 │ │ └── test/ # 单元测试 │ └── pom.xml # Maven 依赖管理 │ ├── blog-frontend/ # Vue3 前端 │ ├── src/ │ │ ├── views/ # 页面组件 (如 ArticleList.vue) │ │ ├── router/ # 路由配置 │ │ ├── stores/ # 状态管理 (如 Pinia) │ │ ├── api/ # API 请求封装 (如 axios 实例) │ │ └── main.js # 应用入口 │ ├── public/ │ ├── index.html │ ├── package.json │ └── vite.config.js │ ├── database/ # 数据库脚本 │ └── init.sql │ ├── README.md # 项目说明文档└── .gitignore # Git 忽略文件配置五、快速启动与验证1. 后端启动cd blog-backend ./mvnw spring-boot:run # 或使用 Maven mvn spring-boot:run访问http://localhost:8080/api/articles测试 API 。2. 前端启动cd blog-frontend npm install npm run dev访问http://localhost:5173操作前端界面。3.接口测试 (使用 curl)# 创建文章 curl -X POST http://localhost:8080/api/articles \ H Content-Type: application/json \ -d {title:第一篇博客,content:Hello World!,author:张三} # 查询文章列表 curl http://localhost:8080/api/articles # 更新文章 (假设id为1) curl -X PUT http://localhost:8080/api/articles/1 \ H Content-Type: application/json \ -d {title:更新后的标题,content:更新内容,author:李四} # 删除文章 (假设id为1) curl -X DELETE http://localhost:8080/api/articles/1六、仓库准备与提交1. 本地 Git 初始化# 在项目根目录 (blog-demo) 执行 git init git add . git commit -m Initial commit: Spring Boot Vue3 CRUD Blog Demo2. 推送到远程仓库 (以 GitHub 为例)# 在 GitHub 上创建新仓库例如名为 springboot-vue3-blog-demo git remote add origin https://github.com/your-username/springboot-vue3-blog-demo.git git branch -M main git push -u origin main3.README.md核心内容示例# Spring Boot Vue3 博客系统 CRUD Demo 一个完整的前后端分离博客系统示例涵盖文章的增加、删除、修改、查询功能。 ## 技术栈 **后端**: Spring Boot 3, Spring Data JPA, MySQL, RESTful API - **前端**: Vue3, Composition API, Axios, Vite - **数据库**: MySQL 8.0 ## 快速开始 1. 克隆项目: git clone https://github.com/your-username/springboot-vue3-blog-demo.git 2. 导入数据库: 执行 database/init.sql 3. 启动后端: cd blog-backend mvn spring-boot:run 4. 启动前端: cd blog-frontend npm install npm run dev 5. 访问前端: http://localhost:5173 ##核心功能 文章列表展示 新建/编辑/删除文章 基于 RESTful API 的前后端通信 ## 接口文档 GET /api/articles获取所有文章 - POST /api/articles - 创建新文章 PUT /api/articles/{id}更新文章 DELETE /api/articles/{id}删除文章通过以上步骤你将拥有一个结构清晰、功能完整、可直接运行和展示的 CRUD Demo 项目仓库完全符合 GitHub/Gitee 的托管要求 。参考来源SpringBoot仓库管理系统实战从架构设计到代码实现深度解析半小时搭建SpringBootVue3博客系统全栈开发实战指南计算机毕业设计实战Java/Python/PHP/Node.js构建个人记账系统一小时搭建Spring BootVue3博客系统从环境配置到部署上线基于SpringBoot的校园二手交易平台从零搭建与毕设实战指南