依赖选择
pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.12</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>springboot_mybatis_CRUD</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot_mybatis_CRUD</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter-test</artifactId> <version>2.3.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <image> <builder>paketobuildpacks/builder-jammy-base:latest</builder> </image> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </pluginRepository> </pluginRepositories> </project>
目录结构
yaml配置文件:
server: port: 8087 spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/aaa?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapping/*Mapper.xml type-aliases-package: com.example.entity.demo logging: level: com: example: mapper : debug
usercontroller
package com.example.springboot_mybatis_crud.controller; import com.example.springboot_mybatis_crud.entity.User; import com.example.springboot_mybatis_crud.mapper.UserMapper; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; @RestController @RequestMapping("/test") public class UserController { @Resource private UserMapper userMapper; @GetMapping("/delete/{id}") public int delete(@PathVariable Integer id){ return userMapper.deleteById(id); } @GetMapping("/selectAll") public List<User> selectAll() { List<User> userList = userMapper.selectAll(); return userList; } @PostMapping("/add/") public int addUser(@RequestBody User user) { return userMapper.Add(user); } @PostMapping("/update/") public int updateUser(@RequestBody User user) { return userMapper.Update(user); } @GetMapping("/select/{name}") public List<User> selectById(@PathVariable String name){ return userMapper.selectByName(name); } }
usermapper
import com.example.springboot_mybatis_crud.entity.User; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserMapper { @Insert("INSERT INTO user (name, sex, age, address) VALUES (#{name}, #{sex}, #{age}, #{address})") int Add(User user); @Update("update user set name = #{name},sex = #{sex} ,age = #{age},address = #{address} where id = #{id}") int Update(User user); @Delete("DELETE FROM user WHERE id = #{id}") int deleteById(@Param("id") Integer id); @Select("select * from user") List<User> selectAll(); @Select("select * from user where name = #{name}") List<User> selectByName(@Param("name") String name); }
启动类
mapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.springboot_mybatis_crud.mapper.UserMapper"> </mapper>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Management</title> <!-- 导入Element UI的CSS文件 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> </head> <body> <div id="app"> <div style="margin: 10px 0"> <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="one.name"></el-input> <el-button class="ml-5" type="primary" @click="load">搜索</el-button> <el-button type="warning" @click="reset">重置</el-button> </div> <el-table :data="userList" border stripe :header-cell-class-name="'headerBg'"> <el-table-column prop="id" label="ID" width="80"></el-table-column> <el-table-column prop="name" label="姓名" width="80"></el-table-column> <el-table-column prop="sex" label="性别" width="80"></el-table-column> <el-table-column prop="address" label="住址" width="140"></el-table-column> <el-table-column prop="age" label="年龄" width="80"></el-table-column> <el-table-column label="操作" width="370" align="center"> <template slot-scope="scope"> <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button> <el-popconfirm class="ml-5" confirm-button-text='确定' cancel-button-text='我再想想' icon="el-icon-info" icon-color="red" title="您确定删除吗?" @confirm="del(scope.row.id)" > <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button> </el-popconfirm> </template> </el-table-column> </el-table> <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button> <el-dialog title="用户信息" :visible.sync="dia" width="30%" > <el-form label-width="80px" size="small"> <el-form-item label="用户名"> <el-input v-model="form.name" autocomplete="off"></el-input> </el-form-item> <el-form-item label="性别"> <el-input v-model="form.sex" autocomplete="off"></el-input> </el-form-item> <el-form-item label="年龄"> <el-input v-model="form.age" autocomplete="off"></el-input> </el-form-item> <el-form-item label="地址"> <el-input v-model="form.address" autocomplete="off"></el-input> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dia = false">取 消</el-button> <el-button type="primary" @click="addUser">确 定</el-button> <el-button type="primary" @click="updateUser">确 定 修 改</el-button> </div> </el-dialog> </div> <!-- 导入Vue.js和Element UI的JS文件 --> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> new Vue({ el: '#app', data: { userList: [], form:{}, dia:false, one:{} }, methods: { reset() { this.one.name = "" this.fetchUsers(); }, load() { fetch('http://localhost:8087/test/select/'+this.one.name) .then(response => response.json()) .then(data => { this.userList = data; }) .catch(error => { console.error('Error:', error); }); }, handleEdit(row) { this.form = JSON.parse(JSON.stringify(row)) this.dia = true }, handleAdd() { this.dia = true this.form = {} }, addUser() { if (this.form.name && this.form.sex && this.form.age && this.form.address) { fetch('http://localhost:8087/test/add/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) }) .then(res => { this.dia = false; this.fetchUsers(); }) .catch(error => { console.error('Error:', error); }); } else { // 如果有任何一个属性为空,可以显示错误信息或者进行其他处理 window.alert("属性不能为空") } } , updateUser() { // 实现更新用户的方法 if (this.form.name && this.form.sex && this.form.age && this.form.address) { fetch('http://localhost:8087/test/update/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) }) .then(res => { this.dia = false; this.fetchUsers(); }) .catch(error => { console.error('Error:', error); }); } else { // 如果有任何一个属性为空,可以显示错误信息或者进行其他处理 window.alert("属性不能为空") } }, del(id) { // 实现删除用户的方法 fetch('http://localhost:8087/test/delete/' + id).then(res => { this.fetchUsers(); }) }, fetchUsers() { fetch('http://localhost:8087/test/selectAll') .then(response => response.json()) .then(data => { this.userList = data; }) .catch(error => { console.error('Error:', error); }); } }, mounted() { this.fetchUsers(); // 页面加载时获取用户列表 } }); </script> </body> </html>