欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 基于SpringBoot和MybatisPlus实现通用Controller

基于SpringBoot和MybatisPlus实现通用Controller

2025/3/17 13:13:25 来源:https://blog.csdn.net/qq_38599266/article/details/146243519  浏览:    关键词:基于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> {@Autowiredprivate 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测试

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词