介绍:
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;
}
}