开发者

SpringBoot和MybatisPlus实现通用Controller示例

开发者 https://www.devze.com 2025-03-15 15:04 出处:网络 作者: 呱呱123#
目录1.定义通用controller2.创建业务实体和mapper接口,基于SpringBoot和MyBATisPlus实现通用Controller,只需要创建实体类和mapper接口,单表增删改查接口就已经实现,编程客栈提升开发效率
目录
  • 1.定义通用controller
  • 2.创建业务实体和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;
imandroidport 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 entityNa编程客栈me) throws Exception {
        javascriptString 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 MybatisPlus 通用Controller内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号