DEV Community

Woody
Woody

Posted on

Use chatgpt create a SpringBoot + MyBatis CRUD code

当然可以!下面我会为你生成一个完整的包含 CRUD(增删改查)功能 的 Spring Boot + MyBatis 项目框架,并附上简单的前端页面(使用 Thymeleaf 进行渲染)。这个项目将以一个简单的“用户管理系统”为例,包含字段:ID、姓名、邮箱。


📁 项目结构

crud-demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com.example.crud/
│   │   │       ├── controller/
│   │   │       ├── mapper/
│   │   │       ├── model/
│   │   │       ├── service/
│   │   │       ├── CrudDemoApplication.java
│   │   └── resources/
│   │       ├── mapper/
│   │       ├── templates/
│   │       ├── application.yml
│   └── test/
│
├── pom.xml
Enter fullscreen mode Exit fullscreen mode

✅ 1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>crud-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- MyBatis + MySQL -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- Thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- Lombok(可选) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot Maven Plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Enter fullscreen mode Exit fullscreen mode

✅ 2. application.yml

server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/crud_db?useSSL=false&serverTimezone=UTC
    username: root
    password: yourpassword
  thymeleaf:
    cache: false

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.crud.model
Enter fullscreen mode Exit fullscreen mode

✅ 3. MySQL 表结构

CREATE DATABASE crud_db;
USE crud_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

✅ 4. 实体类 User.java

package com.example.crud.model;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String name;
    private String email;
}
Enter fullscreen mode Exit fullscreen mode

✅ 5. Mapper 接口 UserMapper.java

package com.example.crud.mapper;

import com.example.crud.model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    List<User> findAll();
    User findById(Integer id);
    int insert(User user);
    int update(User user);
    int deleteById(Integer id);
}
Enter fullscreen mode Exit fullscreen mode

✅ 6. Mapper XML resources/mapper/UserMapper.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.crud.mapper.UserMapper">
    <select id="findAll" resultType="User">
        SELECT * FROM users
    </select>

    <select id="findById" parameterType="int" resultType="User">
        SELECT * FROM users WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="User">
        INSERT INTO users(name, email) VALUES(#{name}, #{email})
    </insert>

    <update id="update" parameterType="User">
        UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
    </update>

    <delete id="deleteById" parameterType="int">
        DELETE FROM users WHERE id = #{id}
    </delete>
</mapper>
Enter fullscreen mode Exit fullscreen mode

✅ 7. Service 类

package com.example.crud.service;

import com.example.crud.mapper.UserMapper;
import com.example.crud.model.User;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    private final UserMapper userMapper;
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public List<User> listAll() {
        return userMapper.findAll();
    }

    public User get(Integer id) {
        return userMapper.findById(id);
    }

    public void save(User user) {
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.update(user);
        }
    }

    public void delete(Integer id) {
        userMapper.deleteById(id);
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ 8. 控制器 UserController.java

package com.example.crud.controller;

import com.example.crud.model.User;
import com.example.crud.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/users")
public class UserController {
    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public String list(Model model) {
        model.addAttribute("users", userService.listAll());
        return "user-list";
    }

    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("user", new User());
        return "user-form";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Integer id, Model model) {
        model.addAttribute("user", userService.get(id));
        return "user-form";
    }

    @PostMapping("/save")
    public String save(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/users";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/users";
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ 9. 前端页面(Thymeleaf)

📄 templates/user-list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User List</title>
</head>
<body>
    <h1>Users</h1>
    <a th:href="@{/users/add}">Add User</a>
    <table border="1">
        <tr>
            <th>ID</th><th>Name</th><th>Email</th><th>Actions</th>
        </tr>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
            <td>
                <a th:href="@{'/users/edit/' + ${user.id}}">Edit</a> |
                <a th:href="@{'/users/delete/' + ${user.id}}"
                   onclick="return confirm('Confirm delete?')">Delete</a>
            </td>
        </tr>
    </table>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

📄 templates/user-form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Form</title>
</head>
<body>
    <h1>User Form</h1>
    <form th:action="@{/users/save}" method="post" th:object="${user}">
        <input type="hidden" th:field="*{id}" />
        Name: <input type="text" th:field="*{name}" /><br/>
        Email: <input type="text" th:field="*{email}" /><br/>
        <button type="submit">Save</button>
    </form>
    <a th:href="@{/users}">Back to list</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

✅ 10. 启动类 CrudDemoApplication.java

package com.example.crud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CrudDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrudDemoApplication.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ 使用方式

  1. 将项目导入 IDEA;
  2. 配置数据库连接;
  3. 启动 MySQL 并创建数据库和表;
  4. 启动应用,访问 http://localhost:8080/users
  5. 就能进行 CRUD 操作了。

如你需要完整的打包源码(zip 文件)、前端改为 Vue + 接口化 API,或想扩展为 RESTful 风格,也可以告诉我,我可以继续帮你生成对应内容。是否需要打包为一个完整 zip 文件?

Top comments (0)