基于spring-springmvc-mybatisplus(SSM)封装的BaseController

介绍:

        mybatisplus封装了dao层和service层,使得实现接口就能解放单表的增删改查,在此基础上,实现了controller层的增删改查以及列表查询和模糊查询,并且使用了swagger以及结果封装集

具体实现要求:

* 1.继承BaseController需要在类上声明 M--继承了IService,T--pojo类
* 2.模糊查询的条件需要封装到相应的Vo中,需要有get和set方法,需要添加无参构造方法
* 3.将pojo属性名转化为数据库字段名,要求java中驼峰命名,数据库中为下划线分割,例如hotelName---hotel_name
* 4.swagger统一命名,无法改变
* 5.Controller层与Vo层命名需要统一,例如 TestController---TestVo,放在平级包下,com.gxa.admin.controller---com.gxa.admin.vo

代码实现:

package com.xxx.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xxx.admin.vo.QueryVo;
import com.xxx.core.exception.CustomerException;
import com.xxx.core.result.Result;
import com.xxx.core.result.ResultUtils;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Stream;


/**
 * @PACKAGE_NAME: com.xxx.admin.controller
 * @AUTHOR: WCY
 * @TIME: 2021-08-07   17:11
 *
 * 1.继承BaseController需要在类上声明 M--继承了IService,T--pojo类
 * 2.模糊查询的条件需要封装到相应的Vo中,需要有get和set方法,需要添加无参构造方法
 * 3.将pojo属性名转化为数据库字段名,要求java中驼峰命名,数据库中为下划线分割,例如hotelName---hotel_name
 * 4.swagger统一命名,无法改变
 * 5.Controller层与Vo层命名需要统一,例如 TestController---TestVo,放在平级包下,com.gxa.admin.controller---com.gxa.admin.vo
 */


@Api(tags = "BaseController")
public class BaseController<M extends IService<T>, T> {

    protected Logger logger = LoggerFactory.getLogger (BaseController.class);

    @Autowired
    private M iService;

    private static Map map = new HashMap();

    static {

        try {

            String stringC = BaseController.class.getPackage ().toString ().substring (BaseController.class.getPackage ().toString ().indexOf ("com") );

            String stringV = stringC.replace ("controller", "vo");

            List classNameControl = BaseController.getClassName (BaseController.class, stringC);

            List classNameVo = BaseController.getClassName (QueryVo.class, stringV);

            for (Object clazz:classNameControl) {

                for (Object clazz1: classNameVo) {

                    if (BaseController.getCName ((Class) clazz).equals (BaseController.getVName ((Class) clazz1)) ){

                        map.put(clazz,clazz1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }

    }
    Class clazz = (Class)map.get (this.getClass ());
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有",notes = "查询所有,page默认为1,pageSize默认为5,传递为json格式",httpMethod = "POST",authorizations = {@Authorization(value = "token")})
    @ApiResponses ({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse (code = 404, message = "请求路径错误")
    })
    protected <clazz> Result list(@RequestBody @ApiParam(name = "iVo", value = "查询list所需参数") clazz iVo) throws Exception {

        Map map1 = new HashMap();
        Map map2 = new LinkedHashMap ();
        map1.put("page",1);
        map1.put("pageSize",5);
        map2 = (Map) iVo;

        for (Object key: map2.keySet () ){
            map1.put(key, map2.get(key));
        }

        Long page1 = Long.valueOf (map1.get ("page").toString ());

        Long pageSize = Long.valueOf (map1.get ("pageSize").toString ());

        //设置分页条件
        Page<T> page = new Page<T>(page1, pageSize);

        //准备查询条件
        QueryWrapper<T> queryWrapper = new QueryWrapper<T>();

        QueryWrapper queryWrapper1 = this.findGetMethod (clazz, map1,queryWrapper);

        Page<T> iPage = iService.page (page, queryWrapper1);

        return ResultUtils.buildSuccess (iPage.getRecords (), iPage.getTotal ());
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据id查询数据",notes = "result风格查询接口,最后的请求路径为 携带的id",httpMethod = "POST",authorizations = {@Authorization(value = "token")})
    @ApiResponses ({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse (code = 404, message = "请求路径错误")
    })
    protected Result findHotelById(@PathVariable("id") String id){

        return ResultUtils.buildSuccess(iService.getById (id));
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @ApiOperation(value = "添加接口",notes = "添加接口",httpMethod = "GET",authorizations = {@Authorization(value = "token")})
    @ApiResponses ({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse (code = 404, message = "请求路径错误")
    })
    protected Result add(@RequestBody  @ApiParam(name = "iPojo", value = "添加iPojo的 json") T iPojo){

        iService.save(iPojo);

        return ResultUtils.buildSuccess();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "修改接口",notes = "修改接口",httpMethod = "POST",authorizations = {@Authorization(value = "token")})
    @ApiResponses ({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse (code = 404, message = "请求路径错误")
    })
    protected Result update(@RequestBody @ApiParam(name = "iPojo", value = "修改 iPojo的json")T iPojo){

        iService.updateById (iPojo);

        return ResultUtils.buildSuccess();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "根据id删除",notes = "最后的请求路径为携带的 id",httpMethod = "GET",authorizations = {@Authorization(value = "token")})
    @ApiResponses ({
            @ApiResponse(code = 400, message = "请求参数没有填好"),
            @ApiResponse (code = 404, message = "请求路径错误")
    })
    protected Result delete(@PathVariable("id") Long id){

        iService.removeById (id);

        return ResultUtils.buildSuccess();
    }

    //用于将pojo属性名转化为数据库字段名,要求java中驼峰命名,数据库中为下划线分割
    //private java.lang.String com.gxa.admin.vo.HotelVo.hotelName
    private  String conversion(String field) throws CustomerException {

        int index = field.lastIndexOf (".");

         field = field.substring (index+1, field.length ());

            String filedName = "";

            char[] chars = field.toCharArray ();

            for (int i = 0; i < chars.length; i++) {

                if (Character.isUpperCase (chars[i])){

                    filedName = filedName + "_";

                }

                filedName = filedName + Character.toLowerCase(chars[i]);
            }

            return filedName;
    }

    //用于获取对应属性的get方法
    private  QueryWrapper findGetMethod(Class < ? > clazz, Map map,QueryWrapper queryWrapper) throws Exception{


        //遍历获取到的属性
        for (Object field : map.keySet()) {

            //设置属性访问权限
//            field.setAccessible(true);

            //调用静态方法获取对应属性的get方法
            Method getterMethod = clazz.getMethod ("get" + field.toString ().substring (0,1).toUpperCase() + field.toString ().substring(1));

            logger.info("获取的get方法为:{}", getterMethod.getName ());

            if (getterMethod.getName ().contains ("Page") || getterMethod.getName ().contains ("PageSize")||getterMethod.getName ().contains ("StartIndex")){

                continue;
            }

            //如果调用get方法后获得结果不为空
            if (!StringUtils.isEmpty (map.get (field).toString ())){

                logger.info("调用的get方法为:{}", getterMethod.getName ());

                //不为空则将查询条件添加进去
                queryWrapper.like (this.conversion (field.toString ()),map.get(field).toString ());

            }

        }

        return queryWrapper;

    }

    //获取相应类的所有子类,通过扫描包来查找
     public static List getClassName(Class clazz ,String packageName) throws Exception {

        List list = new ArrayList ();

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);

        provider.addIncludeFilter(new AssignableTypeFilter (clazz));

        Set<BeanDefinition> components = provider.findCandidateComponents (packageName);

        for (BeanDefinition beanDefinition : components){

            Class<?> aClass = Class.forName (beanDefinition.getBeanClassName ());

            if (!aClass.getName ().contains (clazz.getName ())){

                list.add(aClass);
            }
        }

        return list;
    }

    //通过类的全限定名获取类名(除后缀)  class com.gxa.admin.controller.TestController
    private static String getCName(Class clazz){

        String name = clazz.getName ();

        String controller = name.substring (name.lastIndexOf (".") + 1).replace ("Controller","");

        return controller;
    }

    //通过类的全限定名获取类名(除后缀)  class com.gxa.admin.vo.QueryVo
    private static String getVName(Class clazz){

        String name = clazz.getName ();

        String vo = name.substring (name.lastIndexOf (".") + 1).replace ("Vo", "");

        return vo;
    }

}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
这个网上书城项目采用了当前最流行的框架spring-springmvc-mybatis设计。这个项目旨在提供一个方便、快捷的购书平台,用户可以通过该平台浏览、搜索并购买自己喜欢的图书。 在这个项目中,我们使用了Spring作为项目的核心框架,它提供了依赖注入和面向切面编程等功能,使得项目的开发更加简洁和易于维护。Spring MVC作为项目的Web框架,负责将用户的请求路由到对应的Controller,并负责视图的渲染和返回。而MyBatis则是作为持久层框架,将数据库的操作和Java代码的实现解耦,提供了灵活的SQL映射和缓存机制。 在这个网上书城项目中,我们设计了一套完整的功能模块:用户管理模块、图书管理模块、订单管理模块等。用户可以通过注册、登录等功能来进行用户管理,并可以在平台上对图书进行购买、收藏等操作。同时,平台还提供了搜索功能,用户可以根据图书的名称、作者等进行快速查找。 这个项目的设计更加便于扩展和维护,使用了分层架构,将业务逻辑、持久层和展示层进行了有效的分离。同时,也采用了面向接口编程的思想,降低了模块之间的耦合度,提高了代码的复用性和可测试性。 总之,这个网上书城项目基于spring-springmvc-mybatis框架的设计,充分利用了各自的优势,提供了一个高效、稳定和易于维护的购书平台。期望能为用户提供良好的购书体验,并为图书销售行业的发展做出贡献。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值