在上一节我们已经引入了我们当前工程的所需要的所有的maven依赖,因此本章我们将开始集成swagger2、以及我们抽象实现类的编写,首先大家打开csdn这个工程建好自己相应的包的结构如下所示:
common底下的包主要是用来存放相应的抽象实现类、配置文件、工具类等。
base:主要用于存放抽象实现类,后续我们所有的dao、service、controller都将继承我们这里所编写的抽象实现类。
config:主要用于存放我们的所有的配置文件的配置类,aop(切面)、init(初始化数据加载)、security(权限控制配置)、swagger(swagger配置类)、webmvc(mvc配置类)。
1、接着在我们的config的swagger目录底下创建SwaggerConfig.java文件,文件内容如下:
package com.mongo.common.config.swagger;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/*
* 类描述:
* @auther linzf
* @create 2018/3/30 0030
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private Environment env;
@Bean
public Docket createRestApi() {
Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
// 除非是在开发环境中否则不开启swagger2
String active = env.getProperty("spring.profiles.active");
if(!active.equalsIgnoreCase("dev")){
return false;
}
Class<?> declaringClass = input.declaringClass();
if (declaringClass == BasicErrorController.class)// 排除
return false;
if(declaringClass.isAnnotationPresent(RestController.class)) // 被注解的类
return true;
if(input.isAnnotatedWith(ResponseBody.class)) // 被注解的方法
return true;
return false;
}
};
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(predicate)
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("mongodb 接口测试专用页面!")//大标题
.version("1.0")//版本
.build();
}
}
2、接着我们在我们的common的base目录底下创建我们的抽象实现类
在我们实现以下的抽象实现类的时候,我们首先要先实现以下的两个工具类,分别是util的common目录的CommonUtil.java和util的json目录的JsonHelper.java文件,二者的文件内容如下:
package com.mongo.common.util.common;
/*
* 类描述:
* @auther linzf
* @create 2018/4/11 0011
*/
public class CommonUtil {
/**
* 将首字母变小写
* @param str
* @return
*/
public static String toFirstCharLowerCase(String str){
char[] columnCharArr = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < columnCharArr.length; i++) {
char cur = columnCharArr[i];
if(i==0){
sb.append(Character.toLowerCase(cur));
}else{
sb.append(cur);
}
}
return sb.toString();
}
}
package com.mongo.common.util.json;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* 类描述:json工具类
* @auther linzf
* @create 2017/8/23 0023
*/
public class JsonHelper {
private static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
// 将JSON转换成Map,其中valueClz为Map中value的Class,keyArray为Map的key
public static Map json2Map(Object[] keyArray, String json, Class valueClz) {
JSONObject jsonObject = JSONObject.fromObject(json);
Map classMap = new HashMap();
for (int i = 0; i < keyArray.length; i++) {
classMap.put(keyArray[i], valueClz);
}
return (Map) JSONObject.toBean(jsonObject, Map.class, classMap);
}
/***
* 将对象转换为传入类型的List
*
* @param object
* @param objectClass
* @return
*/
public static <T> Collection<T> toList(Object object, Class<T> objectClass) {
JSONArray jsonArray = JSONArray.fromObject(object);
return JSONArray.toCollection(jsonArray, objectClass);
}
/**
* 功能描述:实现将一个object对象转换为json的string字符串
* @param obj
* @return
*/
public static String object2json(Object obj) {
StringBuilder json = new StringBuilder();
if (obj == null) {
json.append("\"\"");
} else if (obj instanceof String || obj instanceof BigDecimal
|| obj instanceof BigInteger) {
json.append("\"").append(string2json(obj.toString())).append("\"");
} else if (obj instanceof Boolean) {
json.append(Boolean.valueOf(obj.toString()));
} else if (obj instanceof Integer || obj instanceof Float
|| obj instanceof Short || obj instanceof Double
|| obj instanceof Long || obj instanceof Byte) {
json.append(obj.toString());
} else if (obj instanceof Date || obj instanceof java.sql.Date) {
json.append("\"").append(sdf.format(obj)).append("\"");
} else if (obj instanceof Object[]) {
json.append(array2json((Object[]) obj));
} else if (obj instanceof List) {
json.append(list2json((List<?>) obj));
} else if (obj instanceof Map) {
json.append(map2json((Map<?, ?>) obj));
} else if (obj instanceof Set) {
json.append(set2json((Set<?>) obj));
} else {
json.append(bean2json(obj));
}
return json.toString();
}
public static String list2json(List<?> list) {
StringBuilder json = new StringBuilder();
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
public static String array2json(Object[] array) {
StringBuilder json = new StringBuilder();
json.append("[");
if (array != null && array.length > 0) {
for (Object obj : array) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
public static String map2json(Map<?, ?> map) {
StringBuilder json = new StringBuilder();
json.append("{");
if (map != null && map.size() > 0) {
for (Object key : map.keySet()) {
json.append(object2json(key));
json.append(":");
json.append(object2json(map.get(key)));
json.append(",");
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}
public static String set2json(Set<?> set) {
StringBuilder json = new StringBuilder();
json.append("[");
if (set != null && set.size() > 0) {
for (Object obj : set) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
public static String string2json(String s) {
if (s == null)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch >= '\u0000' && ch <= '\u001F') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}
return sb.toString();
}
public static String bean2json(Object bean) {
StringBuilder json = new StringBuilder();
json.append("{");
PropertyDescriptor[] props = null;
try {
props = Introspector.getBeanInfo(bean.getClass(), Object.class)
.getPropertyDescriptors();
} catch (IntrospectionException e) {
}
if (props != null) {
for (int i = 0; i < props.length; i++) {
try {
String name = object2json(props[i].getName());
String value = object2json(props[i].getReadMethod().invoke(
bean));
json.append(name);
json.append(":");
json.append(value);
json.append(",");
} catch (Throwable e) {
}
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}
}
2.1、首先在我们的constant目录底下新建一个SystemStaticConst.java通用常量类,主要用于存放常用静态常量。
package com.mongo.common.base.constant;
/**
* Created by Administrator on 2017/8/7 0007.
*/
public class SystemStaticConst {
public final static String RESULT = "success";
public final static boolean SUCCESS = true;
public final static boolean FAIL = false;
public final static String MSG = "msg";
}
2.2、接着编写我们的通用实体类、通用实体类主要包含Pagination(分页实体类)、QueryBase(查询实体类)、QueryField(实体Bean上注解查询的类)、QueryType(实体上查询的枚举类型)。
2.2.1、Pagination:主要是对页面的分页进行封装,代码如下:
package com.mongo.common.base.entity;
import java.util.List;
public class Pagination<T> {
public Pagination(){
super();
}
public Pagination(Integer currentPage,Integer totalPage,Integer totalNumber){
this.currentPage = currentPage;
this.totalPage = totalPage;
this.totalNumber = totalNumber;
}
/**
* 每页显示条数
*/
private Integer pageSize = 8;
/**
* 当前页
*/
private Integer currentPage = 1;
/**
* 总页数
*/
private Integer totalPage = 1;
/**
* 查询到的总数据量
*/
private Integer totalNumber = 0;
/**
* 数据集
*/
private List items;
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getTotalNumber() {
return totalNumber;
}
public void setTotalNumber(Integer totalNumber) {
this.totalNumber = totalNumber;
}
public List getItems() {
return items;
}
public void setItems(List items) {
this.items = items;
}
/**
* 处理查询后的结果数据
*
* @param items 查询结果集
*/
public void build(List items) {
this.setItems(items);
int count = this.getTotalNumber();
int divisor = count / this.getPageSize();
int remainder = count % this.getPageSize();
this.setTotalPage(remainder == 0 ? divisor == 0 ? 1 : divisor : divisor + 1);
}
}
2.2.2、QueryBase:实现对查询实体的封装,代码如下:
package com.mongo.common.base.entity;
public class QueryBase {
/**
* 页数
*/
protected int page;
/**
* 获取一页行数
* */
protected int limit;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
}
2.2.3、QueryType:查询类型的媒介类,主要用于确定那些字段需要在查询的时候使用到,也许在这里大家可能还不是很明白,等到下一章我们开始编写具体的业务实现的时候,大家就会明白该枚举的作用。
package com.mongo.common.base.entity;
/**
* Created by Administrator on 2018/3/30 0030.
*/
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.List;
/**
* <p>
* 查询类型的媒介类<br/>
* 目前有支持三种类型:<br/>
* 1. equals:相等
* 2. like:mongodb的like查询
* 3. in:用于列表的in类型查询
* </p>
*
*/
public enum QueryType {
EQUALS {
@Override
public Criteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value) {
if (check(queryFieldAnnotation, field, value)) {
String queryField = getQueryFieldName(queryFieldAnnotation, field);
return Criteria.where(queryField).is(value.toString());
}
return new Criteria();
}
},
LIKE {
@Override
public Criteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value) {
if (check(queryFieldAnnotation, field, value)) {
String queryField = getQueryFieldName(queryFieldAnnotation, field);
return Criteria.where(queryField).regex(value.toString());
}
return new Criteria();
}
},
IN {
@Override
public Criteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value) {
if (check(queryFieldAnnotation, field, value)) {
if (value instanceof List) {
String queryField = getQueryFieldName(queryFieldAnnotation, field);
// 此处必须转型为List,否则会在in外面多一层[]
return Criteria.where(queryField).in((List<?>)value);
}
}
return new Criteria();
}
};
private static boolean check(QueryField queryField, Field field, Object value) {
return !(queryField == null || field == null || value == null);
}
public abstract Criteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value);
/**
* 如果实体bean的字段上QueryField注解没有设置attribute属性时,默认为该字段的名称
*
* @param queryField
* @param field
* @return
*/
private static String getQueryFieldName(QueryField queryField, Field field) {
String queryFieldValue = queryField.attribute();
if (!StringUtils.hasText(queryFieldValue)) {
queryFieldValue = field.getName();
}
return queryFieldValue;
}
}
2.2.4、QueryField:用于实体Bean的属性上的注解,注解有两个属性可以设置,type表示查询类似,默认为equals,此块也是等到下一章具体使用的时候再和大家详细介绍,代码如下所示:
package com.mongo.common.base.entity;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>
* 用于实体Bean的属性上的注解,注解有两个属性可以设置,type表示查询类似,默认为equals<br/>
* attribute表示要查询的属性,默认为空串,在使用时如果为空串,则默认为实体Bean字段的名称
* </p>
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface QueryField {
QueryType type() default QueryType.EQUALS;
String attribute() default "";
}
2.3、接着再我们的base的dao目录底下编写我们的dao层的数据库抽象实现类(MongodbBaseService),代码如下所示:
package com.mongo.common.base.dao;
import com.mongo.common.base.entity.Pagination;
import com.mongo.common.base.entity.QueryBase;
import com.mongo.common.base.entity.QueryField;
import com.mongo.common.util.common.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
/*
* 类描述:
* @auther linzf
* @create 2018/3/30 0030
*/
public abstract class MongodbBaseDao<T,Q extends QueryBase>{
@Autowired
@Qualifier("mongoTemplate")
protected MongoTemplate mongoTemplate;
//保存一个对象到mongodb
public T save(T bean) {
mongoTemplate.save(bean);
return bean;
}
// 根据id删除对象
public void deleteById(T t) {
mongoTemplate.remove(t);
}
// 根据对象的属性删除
public void deleteByCondition(T t) {
Query query = buildBaseQuery(t);
mongoTemplate.remove(query, getEntityClass());
}
// 通过条件查询更新数据
public void update(Query query, Update update) {
mongoTemplate.updateMulti(query, update, this.getEntityClass());
}
// 根据id进行更新
public void updateById(String id, T t) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Update update = buildBaseUpdate(t);
update(query, update);
}
// 通过条件查询实体(集合)
public List<T> find(Query query) {
return mongoTemplate.find(query, this.getEntityClass());
}
public List<T> findByCondition(T t) {
Query query = buildBaseQuery(t);
return mongoTemplate.find(query, getEntityClass());
}
// 通过一定的条件查询一个实体
public T findOne(Query query) {
return mongoTemplate.findOne(query, this.getEntityClass());
}
// 通过ID获取记录
public T get(String id) {
return mongoTemplate.findById(id, this.getEntityClass());
}
// 通过ID获取记录,并且指定了集合名(表的意思)
public T get(String id, String collectionName) {
return mongoTemplate.findById(id, this.getEntityClass(), collectionName);
}
/**
* 通过条件查询,查询分页结果
*/
public Pagination<T> findByPage(Q q) {
Query query = buildBaseQuery(q);
//获取总条数
long totalCount = this.mongoTemplate.count(query, this.getEntityClass());
//总页数
int totalPage = (int) (totalCount/q.getLimit());
int skip = (q.getPage()-1)*q.getLimit();
Pagination<T> page = new Pagination(q.getPage(), totalPage, (int)totalCount);
query.skip(skip);// skip相当于从那条记录开始
query.limit(q.getLimit());// 从skip开始,取多少条记录
List<T> data = this.find(query);
page.build(data);//获取数据
return page;
}
/**
* 根据注解构建Query查询条件
* @param q
* @return
*/
public Query buildBaseQuery(Q q){
Query query = new Query();
Field[] fields = q.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(q);
if (value != null&&!value.equals("")) {
QueryField queryField = field.getAnnotation(QueryField.class);
if (queryField != null) {
if(value instanceof String){
query.addCriteria(queryField.type().buildCriteria(queryField, field, value));
}else{
query.addCriteria(queryField.type().buildCriteria(queryField, field, value));
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return query;
}
// 根据vo构建查询条件Query
private Query buildBaseQuery(T t) {
Query query = new Query();
Field[] fields = t.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(t);
if (value != null) {
QueryField queryField = field.getAnnotation(QueryField.class);
if (queryField != null) {
query.addCriteria(queryField.type().buildCriteria(queryField, field, value));
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return query;
}
private Update buildBaseUpdate(T t) {
Update update = new Update();
Field[] fields = t.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(t);
if (value != null) {
update.set(field.getName(), value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return update;
}
// 获取需要操作的实体类class
@SuppressWarnings("unchecked")
protected Class<T> getEntityClass() {
return ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
protected String getCollection(){
String [] collections = getEntityClass().toString().split("\\.");
return CommonUtil.toFirstCharLowerCase(collections[collections.length-1]);
}
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}
}
2.4、接着再我们的base的service目录底下编写我们的service层的业务抽象实现类(
MongodbBaseDao),代码如下所示:
package com.mongo.common.base.service;
import com.mongo.common.base.dao.MongodbBaseDao;
import com.mongo.common.base.entity.Pagination;
import com.mongo.common.base.entity.QueryBase;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;
public abstract class MongodbBaseService<T,Q extends QueryBase> {
protected abstract MongodbBaseDao<T,Q> getDao();
//保存一个对象到mongodb
public T save(T bean) {
getDao().save(bean);
return bean;
}
// 根据id删除对象
public void deleteById(T t) {
getDao().deleteById(t);
}
/**
* 功能描述:批量删除数据
* @param entityList
* @return
*/
public boolean removeBath(List<T> entityList) throws Exception{
for(T t:entityList){
deleteById(t);
}
return true;
}
// 根据对象的属性删除
public void deleteByCondition(T t) {
getDao().deleteByCondition(t);
}
// 通过条件查询更新数据
public void update(Query query, Update update){
getDao().update(query,update);
}
// 根据id进行更新
public void updateById(String id, T t){
getDao().updateById(id,t);
}
// 通过条件查询实体(集合)
public List<T> find(Query query) {
return getDao().find(query);
}
public List<T> findByCondition(T t){
return getDao().findByCondition(t);
}
public T findOne(Query query){
return getDao().findOne(query);
}
// 通过ID获取记录
public T get(String id){
return getDao().get(id);
}
// 通过ID获取记录,并且指定了集合名(表的意思)
public T get(String id, String collectionName){
return getDao().get(id,collectionName);
}
/**
* 通过条件查询,查询分页结果
*/
public Pagination<T> findByPage(Q q){
return getDao().findByPage(q);
}
}
2.5、接着再我们的base的controller目录底下编写我们的controller层的抽象实现类(
MongodbBaseController),代码如下所示:
package com.mongo.common.base.controller;
import com.mongo.common.base.constant.SystemStaticConst;
import com.mongo.common.base.entity.QueryBase;
import com.mongo.common.base.service.MongodbBaseService;
import com.mongo.common.util.common.CommonUtil;
import com.mongo.common.util.json.JsonHelper;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class MongodbBaseController<T,Q extends QueryBase> {
protected abstract MongodbBaseService<T,Q> getService();
/**添加页面路径*/
public final static String ADDPAGE = "/add";
/**修改页面路径*/
public final static String UPDATEPAGE = "/update";
/**
* Controller基路径
* */
protected String basePath;
/**抽象方法,获取页面基路径
* @throws Exception */
protected String getPageBaseRoot() throws Exception{
if(basePath==null){
basePath = this.getClass().getName();
Pattern p=Pattern.compile(".[a-z|A-z]+.controller.[a-z|A-z]+Controller");
Matcher m=p.matcher(basePath);
if(m.find()){
basePath = m.group();
basePath = basePath.substring(1, basePath.length()-10);
basePath = basePath.replace(".", "/");
basePath = basePath.replace("/controller/", "/");
basePath = CommonUtil.toFirstCharLowerCase(basePath);
basePath = basePath.substring(0,basePath.lastIndexOf("/")+1)+CommonUtil.toFirstCharLowerCase(basePath.substring(basePath.lastIndexOf("/")+1));
}
else{
throw new Exception("获取页面基路径失败");
}
}
return basePath;
}
/**
* 功能描述:直接跳转到更新数据的页面
* @param id
* @return
*/
@RequestMapping(value = "/updatePage",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public String updatePage(String id,Model model) throws Exception{
T entity = getService().get(id);
model.addAttribute("entity",entity);
return getPageBaseRoot()+UPDATEPAGE;
}
/** 跳转到添加对象页面
* @throws Exception */
@RequestMapping(value="/addPage")
public String addPage() throws Exception{
return getPageBaseRoot()+ADDPAGE;
}
/**
* 功能描述:保存数据字典数据
* @param entity
* @return
*/
@RequestMapping(value = "/save",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> save(T entity) throws Exception{
entity = getService().save(entity);
Map<String,Object> result = new HashMap<String, Object>();
if(entity!=null){
result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
result.put(SystemStaticConst.MSG,"增加数据成功!");
result.put("entity",entity);
}else{
result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
result.put(SystemStaticConst.MSG,"增加数据失败!");
}
return result;
}
/**
* 功能描述:更新数据字典数据
* @param entity
* @return
*/
@RequestMapping(value = "/update",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> update(String id,T entity) throws Exception{
Map<String,Object> result = new HashMap<String, Object>();
try{
getService().updateById(id,entity);
result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
result.put(SystemStaticConst.MSG,"更新数据成功!");
result.put("entity",entity);
}catch(Exception e){
result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
result.put(SystemStaticConst.MSG,"更新数据失败!");
}
return result;
}
/**
* 功能描述:实现根据ID来删除数据
* @param entity
* @return
*/
@RequestMapping(value = "/remove",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> remove(T entity) throws Exception{
Map<String,Object> result = new HashMap<String, Object>();
getService().deleteById(entity);
result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
result.put(SystemStaticConst.MSG,"删除数据成功!");
return result;
}
/**
* 功能描述:实现批量删除数据字典的记录
* @param json
* @return
*/
@RequestMapping(value = "/removeBath",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> removeBath(String json) throws Exception{
Map<String,Object> result = new HashMap<String, Object>();
getService().removeBath((List<T>) JsonHelper.toList(json,(Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
result.put(SystemStaticConst.MSG,"删除数据成功!");
return result;
}
/**
* 功能描述:判断当前的字典元素是否已经存在
* @param entity
* @return
*/
@RequestMapping(value = "/isExist",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> isExist(T entity){
Map<String,Object> result = new HashMap<String, Object>();
if(getService().findByCondition(entity).size()>0){
result.put("valid",false);
}else{
result.put("valid",true);
}
return result;
}
}
到此我们完成了我们的swagger和抽象实现类的实现,到本章为止大家虽然可以运行起来项目,可是是看不到实际的效果的,在下一章我们将集成我们的security实现用户的登陆功能。
到此为止的GitHub项目地址:https://github.com/185594-5-27/csdn/tree/master-base-3
上一篇文章地址: 基于spring boot和mongodb打造一套完整的权限架构(二)【MAVEN依赖以及相应配置】
下一篇文章地址: 基于spring boot和mongodb打造一套完整的权限架构(四)【完全集成security】
QQ交流群:578746866