SpringBoot增删改查导入导出操作【模板】

SpringBoot增删改查导入导出操作【模板】

文章目录

  • SpringBoot增删改查导入导出操作【模板】
    • 前期数据库操作
    • IDEA上进行操作
      • [1. 创建 Spring Boot 项目](#1. 创建 Spring Boot 项目)
      • [2. 项目结构](#2. 项目结构)
      • [3. pom.xml文件](#3. pom.xml文件)
      • [4. 配置数据库连接并进行测试](#4. 配置数据库连接并进行测试)
      • [5. 创建实体类](#5. 创建实体类)
      • [6. 创建 MyBatis Mapper](#6. 创建 MyBatis Mapper)
      • [7. 创建服务层](#7. 创建服务层)
      • [8. 创建控制器](#8. 创建控制器)
      • [9. 启动应用程序](#9. 启动应用程序)
      • 10.接口测试

前期数据库操作

创建数据库并添加一个表

sql 复制代码
CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT COMMENT 'id',
  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名',
  `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '密码',
  `nickname` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '昵称',
  `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '邮箱',
  `phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '电话',
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '地址',
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `avatar_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '头像',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

IDEA上进行操作

1. 创建 Spring Boot 项目

注意勾选以下依赖

  • Spring Web
  • MyBatis Framework
  • MySQL Driver
  • Lombok

2. 项目结构

项目创建完成后进行创建controller、mapper 、service、entity包,和resources目录下的mapper包

3. pom.xml文件

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>3.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <!-- Generated by https://start.springboot.io -->
    <groupId>com.wudreamer</groupId>
    <artifactId>springboot2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot2</name>
    <description>springboot2</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>
        <!-- mysql依赖 -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- lombok依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- apache.poi依赖,进行导出数据 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>5.1.1</version>
        </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>3.0.4</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

4. 配置数据库连接并进行测试

src/main/resources/application.yml 中配置数据库连接信息:

yml 复制代码
server:
  port: 8090

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/qing?useUnicode=true & characterEncoding=utf-8 &
      useSSL=true & serverTimezone=Asia/Shanghai
    username: root
    password: root

mybatis:
  mapper-locations: classpath:/Mapper/*.xml
  type-aliases-package: com.wudreamer.springboot2.entity

进行检测数据库是否已连接

5. 创建实体类

在 entity 包中创建 User.java

注意一般有lombok依赖后,可以直接使用@Data注解,而省略getter和setter方法(下面我的@Data注解使用不了)

java 复制代码
package com.wudreamer.springboot2.entity;

import lombok.Data;


/*
* 用户实体类
* 1.注意实体类名要与表明相同
* 2.里面的与表结构内容一一对应
* */
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String nickname;
    private String email;
    private String phone;
    private String address;
    private String createTime;  // 确保包含这个字段
    private String avatarUrl;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

}

6. 创建 MyBatis Mapper

mapper 包中创建 UserMapper.java

java 复制代码
package com.wudreamer.springboot2.mapper;

import com.wudreamer.springboot2.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface UserMapper {
    List<User> findAll();       // 查询所有用户
    User findById(Integer id);  // 根据id查询单个用户
    void insert(User user);     // 插入一个新的用户
    void update(User user);     // 更新一个用户的信息
    void delete(Integer id);    // 根据id删除一个用户

    // 实现分页功能
    int countUsers();  // 统计总数
    // 根据提供的页码(offset)和每页个数(limit)查询用户列表
    List<User> findPage(@Param("offset") int offset, @Param("limit") int limit);
}

同时,创建 UserMapper.xml 文件,存放在 src/main/resources/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.wudreamer.springboot2.mapper.UserMapper">
    <!-- 查询所有用户 -->
    <select id="findAll" resultType="com.wudreamer.springboot2.entity.User">
        SELECT * FROM user
    </select>
    <!-- 查询单个用户 -->
    <select id="findById" parameterType="Integer" resultType="com.wudreamer.springboot2.entity.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
    <!-- 新增单个用户 -->
    <insert id="insert" parameterType="com.wudreamer.springboot2.entity.User">
        INSERT INTO user (username, password, nickname, email, phone, address, create_time, avatar_url)
        VALUES (#{username}, #{password}, #{nickname}, #{email}, #{phone}, #{address}, NOW(), #{avatarUrl})
    </insert>
    <!-- 修改单个用户 -->
    <update id="update" parameterType="com.wudreamer.springboot2.entity.User">
        UPDATE user
        SET username = #{username}, password = #{password}, nickname = #{nickname}, email = #{email},
        phone = #{phone}, address = #{address}, avatar_url = #{avatarUrl}
        WHERE id = #{id}
    </update>
    <!-- 删除单个用户 -->
    <delete id="delete" parameterType="Integer">
        DELETE FROM user WHERE id = #{id}
    </delete>
    <!-- 实现分页查询 -->
    <select id="findPage" resultType="com.wudreamer.springboot2.entity.User">
        SELECT * FROM user LIMIT #{offset}, #{limit}
    </select>
    <!-- 统计用户总数 -->
    <select id="countUsers" resultType="int">
        SELECT COUNT(*) FROM user
    </select>
</mapper>

7. 创建服务层

service 包中创建 UserService.java

java 复制代码
package com.wudreamer.springboot2.service;

import com.wudreamer.springboot2.entity.User;
import com.wudreamer.springboot2.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    private final UserMapper userMapper;    // 注入UserMapper接口,用于数据库操作

    // 构造函数注入UserMapper
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    // 查询所有用户,返回用户列表
    public List<User> findAll() {
        return userMapper.findAll(); // 调用UserMapper的findAll方法
    }

    // 根据id查询单个用户,返回单个用户对象
    public User findById(Integer id) {
        return userMapper.findById(id); // 调用UserMapper的findById方法
    }

    // 插入一个新的用户
    public void insert(User user) {
        userMapper.insert(user); // 调用UserMapper的insert方法
    }

    // 更新一个用户的信息
    public void update(User user) {
        userMapper.update(user); // 调用UserMapper的update方法
    }

    // 根据id删除一个用户
    public void delete(Integer id) {
        userMapper.delete(id); // 调用UserMapper的delete方法
    }

    // 实现分页查询功能,返回分页后的用户列表
    public List<User> findPage(int offset, int limit) {
        return userMapper.findPage(offset, limit); // 调用UserMapper的findPage方法
    }

    // 统计用户总数,返回用户总数
    public int countUsers() {
        return userMapper.countUsers(); // 调用UserMapper的countUsers方法
    }
}

8. 创建控制器

controller 包中创建 UserController.java

java 复制代码
package com.wudreamer.springboot2.controller;

import com.wudreamer.springboot2.entity.User;
import com.wudreamer.springboot2.service.UserService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    private final UserService userService;  // 注入UserService

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 查询所有用户
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }

    // 根据id查询单个用户
    @GetMapping("/{id}")
    public User findById(@PathVariable Integer id) {
        return userService.findById(id);
    }

    // 新增单个用户
    @PostMapping
    public void insert(@RequestBody User user) {
        userService.insert(user);
    }

    // 修改用户
    @PutMapping
    public void update(@RequestBody User user) {
        userService.update(user);
    }

    // 删除单个用户
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        userService.delete(id);
    }

    // 实现分页查询、统计用户总数
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam int page, @RequestParam int size) {
        int offset = (page - 1) * size;     // 获取页码 数据从0开始的
        List<User> users = userService.findPage(offset, size);  // 根据偏移量和大小查询用户分页数据
        int totalCount = userService.countUsers();      // 查询用户总数

        Map<String, Object> result = new HashMap<>();
        result.put("userTotal", totalCount);
        result.put("data", users);
        return result;
    }

    // 实现导出功能
    @GetMapping("/export")
    public void exportUsers(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"users.xlsx\"");

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Users");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("用户名");
        headerRow.createCell(2).setCellValue("昵称");
        headerRow.createCell(3).setCellValue("邮箱");
        headerRow.createCell(4).setCellValue("电话");
        headerRow.createCell(5).setCellValue("地址");

        // 获取用户数据
        List<User> users = userService.findAll();

        // 填充数据
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getUsername());
            row.createCell(2).setCellValue(user.getNickname());
            row.createCell(3).setCellValue(user.getEmail());
            row.createCell(4).setCellValue(user.getPhone());
            row.createCell(5).setCellValue(user.getAddress());
        }

        // 写入响应输出流
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }

        // 关闭工作簿
        workbook.close();
    }

    @PostMapping("/import")
    public ResponseEntity<String> importUsers(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请上传文件");
        }

        List<User> userList = new ArrayList<>();

        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个表单

            // 从第二行开始(假设第一行是表头)
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) continue;

                User user = new User();

                // 读取单元格值时先检查单元格类型
                user.setUsername(getCellValue(row.getCell(1)));
                user.setNickname(getCellValue(row.getCell(2)));
                user.setEmail(getCellValue(row.getCell(3)));
                user.setPhone(getCellValue(row.getCell(4)));
                user.setAddress(getCellValue(row.getCell(5)));

                userList.add(user);
            }

            // 将用户数据保存到数据库
            userList.forEach(userService::insert);

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("读取文件出错: " + e.getMessage());
        }

        return ResponseEntity.ok("用户数据导入成功");
    }

    // 读取单元格的辅助方法
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                // 根据需要处理数字,例如格式化为字符串
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}

9. 启动应用程序

运行启动类

10.接口测试





导出接口测试http://localhost:8090/user/export

相关推荐
shaoweijava13 分钟前
企业车辆管理系统(源码+数据库+报告)
java·数据库·spring boot·mysql
Java&Develop22 分钟前
ShardingSphere-多表关联
java·数据库
吴冰_hogan25 分钟前
MySQL 中的 MVCC:实现高效并发控制
数据库·mysql
eternal__day44 分钟前
数据结十大排序之(选排,希尔,插排,堆排)
java·数据结构·算法·推荐算法
我焦虑的编程日记1 小时前
【期末复习】JavaEE(上)
java·java-ee
o不ok!1 小时前
java中File类
java·开发语言
小小小小关同学1 小时前
【并发容器】ConcurrentLinkedQueue:优雅地实现非阻塞式线程安全队列
java·开发语言·安全
KevinAha1 小时前
MacOS 上以源码形式安装 MySQL 5.7
mysql·macos
熬夜的猪1 小时前
Redis 最佳实践
java·redis·后端
Qzer_4071 小时前
在JVM(Java虚拟机)中,PC寄存器(Program Counter Register)扮演着至关重要的角色。
java·开发语言·jvm