SpringBoot+MyBatis与Vue3的全栈CRUD联调案例
本案例将指导您实现一个简单的全栈增删改查(CRUD)应用。后端使用Spring Boot(基于Java)和MyBatis(ORM框架)提供RESTful API,前端使用Vue 3(基于JavaScript)进行数据交互。应用场景以“用户管理”为例,包括创建用户、查询用户列表、更新用户信息和删除用户。以下内容分步解释,确保真实可靠。

1. 整体架构概述
后端:Spring Boot 应用处理业务逻辑,MyBatis 映射数据库操作,提供 API 端点(如 /api/users)。
前端:Vue 3 使用 Composition API 构建界面,通过 Axios 库调用后端 API。
数据库:假设使用 MySQL,表结构简单(例如:id(主键)、name、email)。
联调:前端和后端独立运行,通过 HTTP 请求交互。分页查询时,可用公式计算页数: $$ \text{总页数} = \left\lceil \frac{\text{总记录数}}{\text{每页大小}} \right\rceil $$ 其中,$\left\lceil \cdot \right\rceil$ 表示向上取整。
2. 后端实现(Spring Boot + MyBatis)
后端负责数据持久化和API暴露。以下步骤基于Spring Boot 3.x 和 MyBatis。

步骤1:项目初始化

使用 Spring Initializr 创建项目,依赖包括:Spring Web、MyBatis Framework、MySQL Driver。
配置文件 application.properties 设置数据库连接:
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations=classpath:mapper/*.xml
步骤2:定义实体和Mapper

实体类 User.java:
public class User {
    private Long id;
    private String name;
    private String email;
    // getters and setters
}
Mapper 接口 UserMapper.java:
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users")
    List<User> findAll();

    @Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(User user);

    @Update("UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}")
    void update(User user);

    @Delete("DELETE FROM users WHERE id=#{id}")
    void delete(Long id);
}
步骤3:创建Controller暴露API

UserController.java 处理 CRUD 请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    @PostMapping
    public void addUser(@RequestBody User user) {
        userMapper.insert(user);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userMapper.update(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userMapper.delete(id);
    }
}
步骤4:运行和测试后端

启动Spring Boot应用:运行 main 类。
使用Postman测试API:
GET http://localhost:8080/api/users 查询用户列表。
POST http://localhost:8080/api/users 添加用户(JSON body:{"name":"张三", "email":"zhangsan@example.com"})。
确保返回状态码200表示成功。
3. 前端实现(Vue 3)
前端使用Vue 3和Axios调用API。假设项目通过Vite创建。

步骤1:项目初始化

创建Vue 3项目:npm create vue@latest,选择TypeScript和Axios。
安装Axios:npm install axios。
步骤2:创建用户管理组件

文件 src/components/UserList.vue:
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';

interface User {
  id: number;
  name: string;
  email: string;
}

const users = ref<User[]>([]);
const newUser = ref({ name: '', email: '' });
const editingUser = ref<User | null>(null);

// 获取用户列表
const fetchUsers = async () => {
  const response = await axios.get('http://localhost:8080/api/users');
  users.value = response.data;
};

// 添加用户
const addUser = async () => {
  await axios.post('http://localhost:8080/api/users', newUser.value);
  newUser.value = { name: '', email: '' };
  fetchUsers();
};

// 更新用户
const updateUser = async () => {
  if (editingUser.value) {
    await axios.put(`http://localhost:8080/api/users/${editingUser.value.id}`, editingUser.value);
    editingUser.value = null;
    fetchUsers();
  }
};

// 删除用户
const deleteUser = async (id: number) => {
  await axios.delete(`http://localhost:8080/api/users/${id}`);
  fetchUsers();
};

onMounted(() => {
  fetchUsers();
});
</script>

<template>
  <div>
    <h2>用户列表</h2>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.name }} - {{ user.email }}
        <button @click="editingUser = { ...user }">编辑</button>
        <button @click="deleteUser(user.id)">删除</button>
      </li>
    </ul>

    <h2 v-if="!editingUser">添加用户</h2>
    <h2 v-else>编辑用户</h2>
    <form @submit.prevent="editingUser ? updateUser() : addUser()">
      <input v-model="editingUser ? editingUser.name : newUser.name" placeholder="姓名" required>
      <input v-model="editingUser ? editingUser.email : newUser.email" placeholder="邮箱" type="email" required>
      <button type="submit">{{ editingUser ? '更新' : '添加' }}</button>
      <button v-if="editingUser" @click="editingUser = null">取消</button>
    </form>
  </div>
</template>
步骤3:集成到主应用

在 src/App.vue 中引入组件:
<script setup>
import UserList from './components/UserList.vue';
</script>

<template>
  <UserList />
</template>
步骤4:运行前端

启动开发服务器:npm run dev。
访问 http://localhost:5173 查看界面。
4. 联调与测试
环境准备:
确保后端运行在 http://localhost:8080,前端运行在 http://localhost:5173。
解决跨域问题:在后端添加CORS配置(在Spring Boot的 @Configuration 类中):
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:5173");
        }
    };
}
测试CRUD操作:
在前端界面添加用户:输入姓名和邮箱,点击“添加”。检查后端数据库是否插入成功。
编辑用户:点击“编辑”,修改信息后“更新”。验证数据库更新。
删除用户:点击“删除”,确认用户从列表消失。
错误处理:如果API调用失败(如404错误),前端可添加 try-catch 显示错误消息。
常见问题解决:
网络错误:确保端口一致,或使用代理(Vite配置 vite.config.ts 设置代理)。
数据不一致:检查后端Controller的路径和方法注解(如 @PostMapping)。
5. 总结
本案例展示了全栈CRUD的完整流程:后端通过Spring Boot和MyBatis提供数据服务,前端Vue 3调用API实现交互。
扩展建议:添加分页功能(后端使用 PageHelper,前端计算页数公式如上),或身份验证(Spring Security)。
完整代码参考:可在 GitHub 搜索类似模板(如 “springboot-vue3-crud”)。
通过以上步骤,您能独立构建和联调应用。如有具体问题,欢迎提供更多细节!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐