SpringBoot和MybatisPlus实现通用Controller示例

 更新时间:2025年03月14日 08:31:30   作者:呱呱123#  
本文主要介绍了SpringBoot和MybatisPlus实现通用Controller示例,只需创建实体类和mapper接口,就可以实现单表的增删改查操作,具有一定的参考价值,感兴趣的可以了解一下

基于SpringBoot和MybatisPlus实现通用Controller,只需要创建实体类和mapper接口,单表增删改查接口就已经实现,提升开发效率

1.定义通用controller

package com.xian.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xian.common.alias.*;
import com.xian.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/api/v1/data")
public class BaseController<T extends Serializable> {
    @Autowired
    private ApplicationContext applicationContext;

    private T entity;

    // 使用泛型和IService来处理通用CRUD操作
    protected <S extends BaseMapper<T>> S getMapper(String entityName) throws Exception {
        String serviceName = entityName + "Mapper"; // 假设服务名与实体名相同
        return (S) applicationContext.getBean(serviceName);
    }

    @GetMapping("/{entityName}/get/{id}")
    public Result get(@PathVariable String entityName, @PathVariable Long id) throws Exception {
        BaseMapper<T> mapper = getMapper(entityName);
        return Result.success(mapper.selectById(id));
    }

    @GetMapping("/{entityName}/all")
    public Result get(@PathVariable String entityName) throws Exception {
        BaseMapper<T> mapper = getMapper(entityName);
        return Result.success(mapper.selectList(new QueryWrapper<>()));
    }


    @PostMapping("/{entityName}/insert")
    public Result insert(@PathVariable String entityName,@RequestBody T entity) throws Exception {
        BaseMapper<T> baseMapper =  getMapper(entityName);
        ValidateService<T> validateService = new ValidateServiceImpl<>();
        validateService.validate(entity,baseMapper);
        baseMapper.insert(entity);
        return Result.success();
    }
    @PutMapping("/{entityName}/update")
    public Result update(@PathVariable String entityName,@RequestBody T entity) throws Exception {
        BaseMapper<T> baseMapper =  getMapper(entityName);
        // 使用Spring注入验证服务
        // 验证数据
        ValidateService<T> validateService = new ValidateServiceImpl<>();
        validateService.validate(entity, baseMapper);
        baseMapper.updateById(entity);
        return Result.success();
    }


    @PutMapping("/{entityName}/delete/{id}")
    public Result update(@PathVariable String entityName,@PathVariable Long id) throws Exception {
        BaseMapper<T> baseMapper =  getMapper(entityName);
        baseMapper.deleteById(id);
        return Result.success();
    }


    @PutMapping("/{entityName}/deleteByIds")
    public Result update(@PathVariable String entityName,@RequestBody Collection<Long> ids) throws Exception {
        BaseMapper<T> baseMapper =  getMapper(entityName);
        baseMapper.deleteBatchIds(ids);
        return Result.success();
    }

    // 可以添加其他通用的增删改查方法...
    @PostMapping("/{entityName}/list")
    public Result update(@PathVariable String entityName, @RequestBody PageRequestVo pageRequest) throws Exception {
        BaseMapper<T> baseMapper =  getMapper(entityName);
        System.out.println("pageRequest = " + pageRequest);
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        List<String> sort = pageRequest.getSorts();
        if (sort!=null&& !sort.isEmpty()) {
            sort.forEach(o -> {
                if (o.endsWith("Asc")) {
                    queryWrapper.orderByAsc(o.replace("Asc", ""));
                }else if (o.endsWith("Desc")) {
                    queryWrapper.orderByDesc(o.replace("Desc", ""));
                }else {
                    queryWrapper.orderByAsc(o);
                }
            });
        }
        if (!MapUtil.isEmpty(pageRequest.getParams())){
            // 处理查询参数
            pageRequest.getParams().forEach((field, values) -> {
                if (values != null && !values.isEmpty()) {
                    if (field.endsWith("Like")) {
                        for (Object value : values) {
                            queryWrapper.like(field.replace("Like",""), value);
                        }
                    }else if (field.endsWith("Is")){
                        for (Object value : values) {
                            queryWrapper.eq(field.replace("Like",""), value);
                        }
                    }else if (field.endsWith("Between")){
                        queryWrapper.between(field.replace("Between",""), values.get(0), values.get(1));
                    }else if (field.endsWith("IsNull")){
                        queryWrapper.isNull(field.replace("IsNull",""));
                    }else if (field.endsWith("IsNotNull")){
                        queryWrapper.isNotNull(field.replace("IsNotNull",""));
                    }else if (field.endsWith("NotIn")){
                        queryWrapper.notIn(field.replace("NotIn",""), values);
                    }else if (field.endsWith("In")){
                        queryWrapper.in(field.replace("In",""), values);
                    }else if (field.endsWith("Gt")){
                        queryWrapper.gt(field.replace("Gt",""), values.get(0));
                    }else if (field.endsWith("Ge")){
                        queryWrapper.ge(field.replace("Ge",""), values.get(0));
                    }else if (field.endsWith("Lt")){
                        queryWrapper.lt(field.replace("Lt",""), values.get(0));
                    }else if (field.endsWith("Le")){
                        queryWrapper.le(field.replace("Le",""), values.get(0));
                    }else if (field.endsWith("Eq")){
                        for (Object value : values) {
                            queryWrapper.eq(field.replace("Eq",""), value);
                        }
                    }else if (field.endsWith("Ne")){
                        queryWrapper.ne(field.replace("Ne",""), values.get(0));
                    }else if (field.endsWith("NotBetween")){
                        queryWrapper.notBetween(field.replace("NotBetween",""), values.get(0), values.get(1));
                    }else {
                        for (Object value : values) {
                            queryWrapper.eq(field, value);
                        }
                    }
                }
            });
        }
        return Result.success(PageInfo.of(baseMapper.selectList(queryWrapper)));
    }

}

2.创建业务实体和mapper接口,

@EqualsAndHashCode(callSuper = true)
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User extends Account {

    @TableId(type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private String name;
    private String avatar;
    private String role;
    private String sex;
    private String phone;
    private String email;
    private String info;
    private String birth;

    @TableField(exist = false)
    private Integer blogCount;
    @TableField(exist = false)
    private Integer likesCount;
    @TableField(exist = false)
    private Integer collectCount;

}

mapper接口:

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

postman测试

到此这篇关于SpringBoot和MybatisPlus实现通用Controller的文章就介绍到这了,更多相关SpringBoot MybatisPlus 通用Controller内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring事务管理中@Transactional失效的8个常见场景与解决方案

    Spring事务管理中@Transactional失效的8个常见场景与解决方案

    在实际开发中,你是否遇到过明明在方法上添加了@Transactional注解,但事务却没有按预期工作,本文将深入剖析Spring事务管理中常见的8个陷阱,帮助你彻底解决这些问题
    2025-11-11
  • java灵活使用mysql中json类型字段存储数据详解

    java灵活使用mysql中json类型字段存储数据详解

    在数据库设计中,面对一对多的关系,如订单和商品,可以考虑使用单表存储而非传统的分表方式,这篇文章主要介绍了java灵活使用mysql中json类型字段存储数据的相关资料,需要的朋友可以参考下
    2024-09-09
  • Java中LinkedHashSet的实现原理详解

    Java中LinkedHashSet的实现原理详解

    这篇文章主要介绍了Java中LinkedHasSet的实现原理详解,LinkedHashSet 是具有可预知迭代顺序的 Set 接口的哈希表和链接列表实现,此实现与HashSet 的不同之处在于,后者维护着一个运行于所有条目的双重链接列表,需要的朋友可以参考下
    2023-09-09
  • springboot使用filter获取自定义请求头的实现代码

    springboot使用filter获取自定义请求头的实现代码

    这篇文章主要介绍了springboot使用filter获取自定义请求头的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-05-05
  • IDEA导入Eclipse项目全过程

    IDEA导入Eclipse项目全过程

    这篇文章介绍了如何将Eclipse项目导入到IntelliJ IDEA,并详细步骤如下:新建一个文件夹,用IntelliJ IDEA打开,将项目导入,等待编译完成,配置项目环境和结构,注意文件夹名称可能不同,配置Tomcat,重新编译项目并启动
    2025-11-11
  • springboot+dynamicDataSource动态添加切换数据源方式

    springboot+dynamicDataSource动态添加切换数据源方式

    这篇文章主要介绍了springboot+dynamicDataSource动态添加切换数据源方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • SpringBoot路径映射实现过程图解

    SpringBoot路径映射实现过程图解

    这篇文章主要介绍了SpringBoot路径映射实现过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • spring注解之@Valid和@Validated的区分总结

    spring注解之@Valid和@Validated的区分总结

    @Validated和@Valid在基本验证功能上没有太多区别,但在分组、注解地方、嵌套验证等功能上有所不同,下面这篇文章主要给大家介绍了关于spring注解之@Valid和@Validated区分的相关资料,需要的朋友可以参考下
    2022-03-03
  • Java阻塞队列必看类:BlockingQueue快速了解大体框架和实现思路

    Java阻塞队列必看类:BlockingQueue快速了解大体框架和实现思路

    这篇文章主要介绍了Java阻塞队列必看类:BlockingQueue快速了解大体框架和实现思路,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • Spring Boot基于 JWT 优化 Spring Security 无状态登录实战指南

    Spring Boot基于 JWT 优化 Spring Security 无状态登录实战指南

    本文介绍如何使用JWT优化SpringSecurity实现无状态登录,提高接口安全性,并通过实际操作步骤展示了如何配置JWT参数、实现JWT登录接口、认证过滤器等,感兴趣的朋友跟随小编一起看看吧
    2025-11-11

最新评论