mybatisplus实现简单的增删改查方法

一、搭建mybatisplus项目

参考博客地址 https://blog.csdn.net/only_foryou/article/details/156913310?spm=1001.2014.3001.5501

以下是简单的方法

java 复制代码
  @Override
    public List<Student> getListByName(String name) {
        return list(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    @Override
    public Page<Student> getPageByName(int pageNum, int pageSize, String name) {
        return page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<Student>()
                .eq(Student::getName, name));
    }

    /**
     * 新增学生
     */
    @Override
    public boolean addStudent(Student student) {
        return save(student);
    }

    /**
     * 批量新增学生
     */
    @Override
    public boolean addStudents(List<Student> students) {
        return saveBatch(students);
    }

    /**
     * 根据ID删除学生
     */
    @Override
    public boolean deleteById(Long id) {
        return removeById(id);
    }

    /**
     * 根据ID批量删除学生
     */
    @Override
    public boolean deleteBatchIds(List<Long> ids) {
        return removeBatchByIds(ids);
    }

    /**
     * 根据条件删除学生
     */
    @Override
    public boolean deleteByCondition(String name) {
        return remove(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    /**
     * 更新学生信息
     */
    @Override
    public boolean updateStudent(Student student) {
        return updateById(student);
    }

    /**
     * 批量更新学生信息
     */
    @Override
    public boolean updateStudents(List<Student> students) {
        return updateBatchById(students);
    }

    /**
     * 条件更新学生信息
     */
    @Override
    public boolean updateByCondition(Student student, String oldName) {
        return update(student, new LambdaQueryWrapper<Student>().eq(Student::getName, oldName));
    }

    /**
     * 根据ID查询学生
     */
    @Override
    public Student getStudentById(Long id) {
        return getById(id);
    }

    /**
     * 根据条件查询单个学生
     */
    @Override
    public Student getOneStudent(String name) {
        return getOne(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    /**
     * 查询所有学生
     */
    @Override
    public List<Student> getAllStudents() {
        return list();
    }

    /**
     * 分页查询所有学生
     */
    @Override
    public Page<Student> getPageList(int pageNum, int pageSize) {
        return page(new Page<>(pageNum, pageSize));
    }

    /**
     * 统计学生数量
     */
    @Override
    public long countAll() {
        return count();
    }

    /**
     * 根据条件统计学生数量
     */
    @Override
    public long countByName(String name) {
        return count(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    /**
     * 判断学生是否存在
     */
    @Override
    public boolean existsById(Long id) {
        return getById(id) != null;
    }

目录结构

具体项目代码

二、entity

java 复制代码
package com.qiu.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * 描述:学生实体类
 *
 * @author: qxd
 * @date: 2025/11/29 22:09
 * @version: 1.0.0
 */
@Data
// 指定表名
@TableName("student")
public class Student {
    /**
     * 学生ID
     */
    @TableId(type = IdType.AUTO)
    private Integer id;

    /**
     * 学生姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 性别
     */
    private String gender;

    /**
     * 邮箱
     */
    private String email;

    /**
     * 电话
     */
    private String phone;

    /**
     * 地址
     */
    private String address;

    /**
     * 创建时间
     */
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
}

**三、**dao

java 复制代码
package com.qiu.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qiu.entity.Student;
import org.apache.ibatis.annotations.Mapper;

/**
 * 描述:学生数据访问接口
 *
 * @author: qxd
 * @date: 2025/11/12 22:11
 * @version: 1.0.0
 */
@Mapper
public interface StudentDao extends BaseMapper<Student> {


}

**四、**Service

java 复制代码
package com.qiu.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qiu.entity.Student;

import java.util.List;

/**
 * 描述:学生服务接口
 *
 * @author: qxd
 * @date: 2025/11/29 22:04
 * @version: 1.0.0
 */
public interface StudentService extends IService<Student> {

    /**
     * 根据姓名获取学生列表
     */
    List<Student> getListByName(String name);

    /**
     * 根据姓名分页查询学生
     */
    Page<Student> getPageByName(int pageNum, int pageSize, String name);

    /**
     * 新增学生
     */
    boolean addStudent(Student student);

    /**
     * 批量新增学生
     */
    boolean addStudents(List<Student> students);

    /**
     * 根据ID删除学生
     */
    boolean deleteById(Long id);

    /**
     * 根据ID批量删除学生
     */
    boolean deleteBatchIds(List<Long> ids);

    /**
     * 根据条件删除学生
     */
    boolean deleteByCondition(String name);

    /**
     * 更新学生信息
     */
    boolean updateStudent(Student student);

    /**
     * 批量更新学生信息
     */
    boolean updateStudents(List<Student> students);

    /**
     * 条件更新学生信息
     */
    boolean updateByCondition(Student student, String oldName);

    /**
     * 根据ID查询学生
     */
    Student getStudentById(Long id);

    /**
     * 根据条件查询单个学生
     */
    Student getOneStudent(String name);

    /**
     * 查询所有学生
     */
    List<Student> getAllStudents();

    /**
     * 分页查询所有学生
     */
    Page<Student> getPageList(int pageNum, int pageSize);

    /**
     * 统计学生数量
     */
    long countAll();

    /**
     * 根据姓名统计学生数量
     */
    long countByName(String name);

    /**
     * 判断学生是否存在
     */
    boolean existsById(Long id);
}

**五、**ServiceImpl

java 复制代码
package com.qiu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiu.dao.StudentDao;
import com.qiu.entity.Student;
import com.qiu.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 描述:
 *
 * @author: qxd
 * @date: 2025/11/19 22:04
 * @version: 1.0.0
 */
@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentDao, Student> implements StudentService {
    @Override
    public List<Student> getListByName(String name) {
        return list(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    @Override
    public Page<Student> getPageByName(int pageNum, int pageSize, String name) {
        return page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<Student>()
                .eq(Student::getName, name));
    }

    /**
     * 新增学生
     */
    @Override
    public boolean addStudent(Student student) {
        return save(student);
    }

    /**
     * 批量新增学生
     */
    @Override
    public boolean addStudents(List<Student> students) {
        return saveBatch(students);
    }

    /**
     * 根据ID删除学生
     */
    @Override
    public boolean deleteById(Long id) {
        return removeById(id);
    }

    /**
     * 根据ID批量删除学生
     */
    @Override
    public boolean deleteBatchIds(List<Long> ids) {
        return removeBatchByIds(ids);
    }

    /**
     * 根据条件删除学生
     */
    @Override
    public boolean deleteByCondition(String name) {
        return remove(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    /**
     * 更新学生信息
     */
    @Override
    public boolean updateStudent(Student student) {
        return updateById(student);
    }

    /**
     * 批量更新学生信息
     */
    @Override
    public boolean updateStudents(List<Student> students) {
        return updateBatchById(students);
    }

    /**
     * 条件更新学生信息
     */
    @Override
    public boolean updateByCondition(Student student, String oldName) {
        return update(student, new LambdaQueryWrapper<Student>().eq(Student::getName, oldName));
    }

    /**
     * 根据ID查询学生
     */
    @Override
    public Student getStudentById(Long id) {
        return getById(id);
    }

    /**
     * 根据条件查询单个学生
     */
    @Override
    public Student getOneStudent(String name) {
        return getOne(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    /**
     * 查询所有学生
     */
    @Override
    public List<Student> getAllStudents() {
        return list();
    }

    /**
     * 分页查询所有学生
     */
    @Override
    public Page<Student> getPageList(int pageNum, int pageSize) {
        return page(new Page<>(pageNum, pageSize));
    }

    /**
     * 统计学生数量
     */
    @Override
    public long countAll() {
        return count();
    }

    /**
     * 根据条件统计学生数量
     */
    @Override
    public long countByName(String name) {
        return count(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
    }

    /**
     * 判断学生是否存在
     */
    @Override
    public boolean existsById(Long id) {
        return getById(id) != null;
    }
}

**六、**Result

java 复制代码
package com.qiu.common;

import lombok.Data;

/**
 * 统一响应结果封装类
 *
 * @param <T>
 * @author: qxd
 * @date: 2025/11/19 22:04
 * @version: 1.0.0
 */
@Data
public class Result<T> {

    // 响应状态码
    private Integer code;
    
    // 响应消息
    private String msg;
    
    // 响应数据
    private T data;

    // 成功状态码
    public static final Integer SUCCESS_CODE = 200;
    
    // 失败状态码
    public static final Integer ERROR_CODE = 500;

    // 构造函数
    private Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 成功响应
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(SUCCESS_CODE, "操作成功", data);
    }

    /**
     * 成功响应(无数据)
     */
    public static <T> Result<T> success() {
        return new Result<>(SUCCESS_CODE, "操作成功", null);
    }

    /**
     * 成功响应(自定义消息)
     */
    public static <T> Result<T> success(String msg, T data) {
        return new Result<>(SUCCESS_CODE, msg, data);
    }

    /**
     * 失败响应
     */
    public static <T> Result<T> error(String msg) {
        return new Result<>(ERROR_CODE, msg, null);
    }

    /**
     * 自定义响应
     */
    public static <T> Result<T> build(Integer code, String msg, T data) {
        return new Result<>(code, msg, data);
    }
}

七、Controller

java 复制代码
package com.qiu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiu.common.Result;
import com.qiu.entity.Student;
import com.qiu.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 描述:demo
 *
 * @author: qxd
 * @date: 2025/11/29 21:54
 * @version: 1.0.0
 */
@Slf4j
@RequestMapping("/student")
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Operation(summary = "hello", description = "hello")
    @GetMapping("/hello")
    public String hello() {
        log.info("hello world");
        return "hello world";
    }

    @Operation(summary = "根据姓名查询学生列表", description = "根据姓名查询学生列表")
    @GetMapping("/getListByName")
    public List<Student> getListByName(@RequestParam("name") String name) {
        return studentService.getListByName(name);
    }

    @Operation(summary = "根据名字分页查询", description = "根据姓名分页查询学生信息")
    @GetMapping("/getPageByName")
    public Page<Student> getPageByName(@RequestParam(defaultValue = "1") int pageNum,
                                       @RequestParam(defaultValue = "10") int pageSize,
                                       @RequestParam("name") String name) {
        return studentService.getPageByName(pageNum, pageSize, name);
    }


    @Operation(summary = "新增学生", description = "添加新的学生信息")
    @PostMapping("/add")
    public Result<Boolean> addStudent(@RequestBody Student student) {
        boolean result = studentService.addStudent(student);
        return Result.success(result);
    }

    @Operation(summary = "批量新增学生", description = "批量添加学生信息")
    @PostMapping("/batchAdd")
    public Result<Boolean> addStudents(@RequestBody List<Student> students) {
        boolean result = studentService.addStudents(students);
        return Result.success(result);
    }

    @Operation(summary = "根据ID删除学生", description = "根据学生ID删除学生信息")
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteById(@PathVariable Long id) {
        boolean result = studentService.deleteById(id);
        return Result.success(result);
    }

    @Operation(summary = "根据ID批量删除学生", description = "根据多个学生ID批量删除学生信息")
    @Parameter(name = "ids", description = "学生ID列表,用逗号分隔,如:1,2,3",
            required = true, schema = @Schema(type = "string"))
    @DeleteMapping("/batchDelete")
    public Result<Boolean> deleteBatchIds(@RequestParam List<Long> ids) {
        boolean result = studentService.deleteBatchIds(ids);
        return Result.success(result);
    }

    @Operation(summary = "根据条件删除学生", description = "根据姓名删除学生信息")
    @DeleteMapping("/deleteByCondition")
    public Result<Boolean> deleteByCondition(@RequestParam String name) {
        boolean result = studentService.deleteByCondition(name);
        return Result.success(result);
    }

    @Operation(summary = "更新学生信息", description = "更新学生的基本信息")
    @PutMapping("/update")
    public Result<Boolean> updateStudent(@RequestBody Student student) {
        boolean result = studentService.updateStudent(student);
        return Result.success(result);
    }

    @Operation(summary = "批量更新学生信息", description = "批量更新学生信息")
    @PutMapping("/batchUpdate")
    public Result<Boolean> updateStudents(@RequestBody List<Student> students) {
        boolean result = studentService.updateStudents(students);
        return Result.success(result);
    }

    @Operation(summary = "条件更新学生信息", description = "根据旧姓名更新学生信息")
    @PutMapping("/updateByCondition")
    public Result<Boolean> updateByCondition(@RequestBody Student student,
                                           @RequestParam String oldName) {
        boolean result = studentService.updateByCondition(student, oldName);
        return Result.success(result);
    }

    @Operation(summary = "根据ID查询学生", description = "根据学生ID获取学生详细信息")
    @GetMapping("/getById/{id}")
    public Result<Student> getStudentById(@PathVariable Long id) {
        Student student = studentService.getStudentById(id);
        return Result.success(student);
    }

    @Operation(summary = "根据条件查询单个学生", description = "根据姓名查询单个学生信息")
    @GetMapping("/getOne")
    public Result<Student> getOneStudent(@RequestParam String name) {
        Student student = studentService.getOneStudent(name);
        return Result.success(student);
    }

    @Operation(summary = "查询所有学生", description = "获取所有学生信息")
    @GetMapping("/getAll")
    public Result<List<Student>> getAllStudents() {
        List<Student> students = studentService.getAllStudents();
        return Result.success(students);
    }

    @Operation(summary = "分页查询所有学生", description = "分页获取所有学生信息")
    @GetMapping("/getPageList")
    public Result<Page<Student>> getPageList(@RequestParam(defaultValue = "1") int pageNum,
                                           @RequestParam(defaultValue = "10") int pageSize) {
        Page<Student> pageResult = studentService.getPageList(pageNum, pageSize);
        return Result.success(pageResult);
    }

    @Operation(summary = "统计学生总数", description = "获取学生总数量")
    @GetMapping("/countAll")
    public Result<Long> countAll() {
        Long count = studentService.countAll();
        return Result.success(count);
    }

    @Operation(summary = "根据姓名统计学生数量", description = "根据姓名统计学生数量")
    @GetMapping("/countByName")
    public Result<Long> countByName(@RequestParam String name) {
        Long count = studentService.countByName(name);
        return Result.success(count);
    }

    @Operation(summary = "判断学生是否存在", description = "根据ID判断学生是否存在")
    @GetMapping("/exists/{id}")
    public Result<Boolean> existsById(@PathVariable Long id) {
        boolean exists = studentService.existsById(id);
        return Result.success(exists);
    }
}

八、config

java 复制代码
package com.qiu.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

九、项目地址

https://gitee.com/qiuxiaodong/demo

项目名称:demo-springboot-mybatisplus01

十、接口地址

http://127.0.0.1:8088/swagger-ui/index.html

相关推荐
言慢行善1 小时前
sqlserver模糊查询问题
java·数据库·sqlserver
专吃海绵宝宝菠萝屋的派大星1 小时前
使用Dify对接自己开发的mcp
java·服务器·前端
大数据新鸟1 小时前
操作系统之虚拟内存
java·服务器·网络
Tong Z1 小时前
常见的限流算法和实现原理
java·开发语言
凭君语未可1 小时前
Java 中的实现类是什么
java·开发语言
He少年2 小时前
【基础知识、Skill、Rules和MCP案例介绍】
java·前端·python
克里斯蒂亚诺更新2 小时前
myeclipse的pojie
java·ide·myeclipse
迷藏4942 小时前
**eBPF实战进阶:从零构建网络流量监控与过滤系统**在现代云原生架构中,**网络可观测性**和**安全隔离**已成为
java·网络·python·云原生·架构
迷藏4942 小时前
**发散创新:基于Solid协议的Web3.0去中心化身份认证系统实战解析**在Web3.
java·python·web3·去中心化·区块链