SpringBoot和MybatisPlus实现通用Controller示例
基于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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
- SpringBoot如何实现调用controller和Service层方法
- springboot中的controller参数映射问题小结
- springboot中Controller内文件上传到本地及阿里云操作方法
- springboot如何通过controller层实现页面切换
- springboot Controller直接返回String类型带来的乱码问题及解决
- SpringBoot之controller参数校验详解
- springboot中@RestController注解实现
- SpringBoot通过注解监测Controller接口的代码示例
- springboot controller参数注入方式
- SpringBoot中@RestControllerAdvice @ExceptionHandler异常统一处理类失效原因分析
相关文章
Spring事务管理中@Transactional失效的8个常见场景与解决方案
在实际开发中,你是否遇到过明明在方法上添加了@Transactional注解,但事务却没有按预期工作,本文将深入剖析Spring事务管理中常见的8个陷阱,帮助你彻底解决这些问题2025-11-11
springboot使用filter获取自定义请求头的实现代码
这篇文章主要介绍了springboot使用filter获取自定义请求头的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下2019-05-05
springboot+dynamicDataSource动态添加切换数据源方式
这篇文章主要介绍了springboot+dynamicDataSource动态添加切换数据源方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01
spring注解之@Valid和@Validated的区分总结
@Validated和@Valid在基本验证功能上没有太多区别,但在分组、注解地方、嵌套验证等功能上有所不同,下面这篇文章主要给大家介绍了关于spring注解之@Valid和@Validated区分的相关资料,需要的朋友可以参考下2022-03-03
Java阻塞队列必看类:BlockingQueue快速了解大体框架和实现思路
这篇文章主要介绍了Java阻塞队列必看类:BlockingQueue快速了解大体框架和实现思路,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-10-10
Spring Boot基于 JWT 优化 Spring Security 无状态登录实战指南
本文介绍如何使用JWT优化SpringSecurity实现无状态登录,提高接口安全性,并通过实际操作步骤展示了如何配置JWT参数、实现JWT登录接口、认证过滤器等,感兴趣的朋友跟随小编一起看看吧2025-11-11


最新评论