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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java 在Word文档中添加艺术字的示例

    Java 在Word文档中添加艺术字的示例

    这篇文章主要介绍了Java 在Word文档中添加艺术字的示例,帮助大家使用Java处理word文档,感兴趣的朋友可以了解下
    2020-09-09
  • Idea配置maven-tomcat-plugin插件实现项目部署

    Idea配置maven-tomcat-plugin插件实现项目部署

    今天小编就为大家分享一篇关于Idea配置maven-tomcat-plugin插件实现项目部署,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Java利用Netty时间轮实现延时任务

    Java利用Netty时间轮实现延时任务

    时间轮是一种可以执行定时任务的数据结构和算法。本文将为大家详细讲解一下Java如何利用Netty时间轮算法实现延时任务,感兴趣的小伙伴可以了解一下
    2022-08-08
  • RestTemplate实现多种底层HTTP客户端类库的切换用法

    RestTemplate实现多种底层HTTP客户端类库的切换用法

    这篇文章主要为大家详细的讲解了RestTemplate实现多种底层HTTP客户端类库的切换示例,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步
    2022-03-03
  • 解决HashMap多线程操作导致死循环问题

    解决HashMap多线程操作导致死循环问题

    文章主要讲述了在多线程环境下,HashMap的并发操作可能导致的死循环问题,包括链表/红黑树结构破坏、扩容过程中的混乱以及读写不一致等,为了解决这些问题,文章建议使用线程安全的ConcurrentHashMap替代HashMap,并介绍了其分段锁机制和优化方案
    2025-01-01
  • 你知道jdk竟有4个random吗

    你知道jdk竟有4个random吗

    这篇文章主要给大家介绍了关于jdk中4个random的相关资料,分别是Random、ThreadLocalRandom、SecureRandom以及SplittableRandom,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2021-06-06
  • spring cloud 的监控turbine-rabbitmq的示例

    spring cloud 的监控turbine-rabbitmq的示例

    这篇文章主要介绍了spring cloud 的监控turbine-rabbitmq的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • 解决Springboot @WebFilter拦截器未生效问题

    解决Springboot @WebFilter拦截器未生效问题

    这篇文章主要介绍了解决Springboot @WebFilter拦截器未生效问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • 解析ConcurrentHashMap: get、remove方法分析

    解析ConcurrentHashMap: get、remove方法分析

    ConcurrentHashMap是由Segment数组结构和HashEntry数组结构组成。Segment的结构和HashMap类似,是一种数组和链表结构,今天给大家普及java面试常见问题---ConcurrentHashMap知识,一起看看吧
    2021-06-06
  • SpringAOP实现自定义接口权限控制

    SpringAOP实现自定义接口权限控制

    本文主要介绍了SpringAOP实现自定义接口权限控制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-11-11

最新评论