├── README.md ├── imgs └── p.png ├── pom.xml ├── restful-api-core ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── restful │ └── api │ └── core │ ├── Rest.java │ ├── advice │ ├── ExceptionAdvice.java │ └── ForbidMethodAdvice.java │ ├── anno │ ├── ForbidMethod.java │ └── Log.java │ ├── controller │ ├── AppController.java │ └── CrudController.java │ ├── ex │ ├── ForbidAccessException.java │ └── NotFindDataException.java │ ├── jackson │ └── CustomObjectMapper.java │ ├── jsonp │ └── JsonpSupportAdvice.java │ ├── log │ ├── LogAdvice.java │ ├── LogApi.java │ └── LogBean.java │ └── util │ ├── IpUtil.java │ └── ValidateUtil.java └── restful-api-web ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── restful │ │ └── api │ │ └── web │ │ ├── component │ │ ├── RestExceptionAdvice.java │ │ └── SwaggerConfig.java │ │ ├── controller │ │ └── BlogController.java │ │ ├── entity │ │ ├── Blog.java │ │ └── User.java │ │ ├── mapper │ │ ├── BlogMapper.java │ │ ├── UserMapper.java │ │ └── xml │ │ │ ├── BlogMapper.xml │ │ │ └── UserMapper.xml │ │ └── service │ │ ├── IBlogService.java │ │ ├── IUserService.java │ │ └── impl │ │ ├── BlogServiceImpl.java │ │ ├── LogServiceImpl.java │ │ └── UserServiceImpl.java ├── resources │ ├── log4j.properties │ ├── properties │ │ └── jdbc.properties │ ├── spring │ │ ├── applicationContext-dao.xml │ │ ├── applicationContext-service.xml │ │ └── servlet-context.xml │ ├── sql │ │ └── restful-api.sql │ └── xml │ │ └── mybatis-config.xml └── webapp │ └── WEB-INF │ └── web.xml └── test └── java └── com └── gen └── MysqlGenerator.java /README.md: -------------------------------------------------------------------------------- 1 | ### restful-api 2 | ### 自动生成Restful风格CRUD接口框架,节约时间关注业务 3 | 4 | ### 技术选型 5 | ------------- 6 | Spring MVC、Mybatis、Mybatis-Plus(Mybatis增强插件)、Mysql、Maven、swagger2 7 | 8 | ### 基本功能 9 | ------------- 10 | 1. 自动生成restful风格CRUD接口,可覆盖,可扩展,可禁止 11 | 2. AOP实现日志记录,开发者可实现LogApi接口灵活处理日志 12 | 3. 全局异常处理,响应统一格式的异常消息 13 | 4. 响应统一格式的JSON数据,日期格式化处理,JSONP支持 14 | 15 | ### 接口文档 16 | ------------- 17 | ![image](https://github.com/alexdoop/restful-api/blob/master/imgs/p.png) 18 | 19 | ### 快速开始 20 | ------------- 21 | 1. git clone https://github.com/alexdoop/restful-api.git 22 | 2. cd ~/restful-api && mvn install 23 | 3. cd restful-api-web && mvn jetty:run 24 | 4. http://localhost:8080/swagger-ui.html 25 | 26 | ### 接口生成 27 | ------------- 28 | 1. 创建表tb_user,字段id(int),userName(varchar),password(varchar),age(int) 29 | 2. 使用test下的MysqlGenerator.java生成model,mapper,xml,service,并拷贝到当前项目对应的目录下 30 | 3. 在controller包下创建UserController,继承CurdController,再无需编写任何代码即可拥有CRDU四个标准的Restful风格接口 31 | 4. 重启项目,over,开发接口就是这么简单 32 | 33 | ### 开发进度 34 | ------------- 35 | 正在努力开发中... 36 | -------------------------------------------------------------------------------- /imgs/p.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/telzhou618/restful-api/9fb01efb0cfbb8992ef8c615150a44872d9d1860/imgs/p.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 4.0.0 5 | com.vaco 6 | restful-api 7 | pom 8 | 0.0.1-SNAPSHOT 9 | restful-api Maven Webapp 10 | http://maven.apache.org 11 | 12 | 13 | 4.12 14 | 4.3.7.RELEASE 15 | 2.0.8 16 | 5.1.32 17 | 1.7.21 18 | 2.7.4 19 | 1.0.19 20 | 3.0.1 21 | 2.4 22 | 5.1.3.Final 23 | 2.7.0 24 | 1.3.1 25 | 2.8.0 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | junit 34 | junit 35 | ${junit.version} 36 | test 37 | 38 | 39 | 40 | com.fasterxml.jackson.core 41 | jackson-annotations 42 | ${jackson.version} 43 | 44 | 45 | com.fasterxml.jackson.core 46 | jackson-databind 47 | ${jackson.version} 48 | 49 | 50 | com.fasterxml.jackson.core 51 | jackson-core 52 | ${jackson.version} 53 | 54 | 55 | 56 | org.slf4j 57 | slf4j-api 58 | ${slf4j.version} 59 | 60 | 61 | org.slf4j 62 | slf4j-log4j12 63 | ${slf4j.version} 64 | 65 | 66 | 67 | javax.servlet 68 | javax.servlet-api 69 | ${servlet-api.version} 70 | 71 | 72 | 73 | com.baomidou 74 | mybatis-plus 75 | ${mybatis-plus.version} 76 | 77 | 78 | 79 | mysql 80 | mysql-connector-java 81 | ${mysql.version} 82 | 83 | 84 | 85 | com.alibaba 86 | druid 87 | ${druid.version} 88 | 89 | 90 | 91 | org.springframework 92 | spring-context 93 | ${spring.version} 94 | 95 | 96 | org.springframework 97 | spring-beans 98 | ${spring.version} 99 | 100 | 101 | org.springframework 102 | spring-webmvc 103 | ${spring.version} 104 | 105 | 106 | org.springframework 107 | spring-jdbc 108 | ${spring.version} 109 | 110 | 111 | org.springframework 112 | spring-aspects 113 | ${spring.version} 114 | 115 | 116 | org.springframework 117 | spring-context-support 118 | ${spring.version} 119 | 120 | 121 | org.springframework 122 | spring-aop 123 | ${spring.version} 124 | 125 | 126 | org.springframework 127 | spring-web 128 | ${spring.version} 129 | 130 | 131 | org.springframework 132 | spring-core 133 | ${spring.version} 134 | 135 | 136 | 137 | 138 | org.hibernate 139 | hibernate-validator 140 | ${hibernate-validator.version} 141 | 142 | 143 | 144 | io.springfox 145 | springfox-swagger2 146 | ${swagger.version} 147 | 148 | 149 | io.springfox 150 | springfox-swagger-ui 151 | ${swagger.version} 152 | 153 | 154 | com.fasterxml 155 | classmate 156 | ${classmate.version} 157 | 158 | 159 | 160 | 161 | commons-lang 162 | commons-lang 163 | ${commons-lang.version} 164 | 165 | 166 | 167 | 168 | com.google.code.gson 169 | gson 170 | ${gson.version} 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | org.apache.maven.plugins 179 | maven-compiler-plugin 180 | 3.0 181 | 182 | 1.8 183 | 1.8 184 | UTF-8 185 | true 186 | 187 | 188 | 189 | 190 | 191 | restful-api-core 192 | restful-api-web 193 | 194 | 195 | -------------------------------------------------------------------------------- /restful-api-core/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.vaco 6 | restful-api 7 | 0.0.1-SNAPSHOT 8 | 9 | restful-api-core 10 | 11 | 12 | 13 | 14 | 15 | junit 16 | junit 17 | test 18 | 19 | 20 | 21 | com.fasterxml.jackson.core 22 | jackson-annotations 23 | 24 | 25 | com.fasterxml.jackson.core 26 | jackson-databind 27 | 28 | 29 | com.fasterxml.jackson.core 30 | jackson-core 31 | 32 | 33 | 34 | org.slf4j 35 | slf4j-api 36 | 37 | 38 | org.slf4j 39 | slf4j-log4j12 40 | 41 | 42 | 43 | javax.servlet 44 | javax.servlet-api 45 | 46 | 47 | 48 | com.baomidou 49 | mybatis-plus 50 | 51 | 52 | 53 | mysql 54 | mysql-connector-java 55 | 56 | 57 | 58 | com.alibaba 59 | druid 60 | 61 | 62 | 63 | org.springframework 64 | spring-context 65 | 66 | 67 | org.springframework 68 | spring-beans 69 | 70 | 71 | org.springframework 72 | spring-webmvc 73 | 74 | 75 | org.springframework 76 | spring-jdbc 77 | 78 | 79 | org.springframework 80 | spring-aspects 81 | 82 | 83 | org.springframework 84 | spring-context-support 85 | 86 | 87 | org.springframework 88 | spring-aop 89 | 90 | 91 | org.springframework 92 | spring-web 93 | 94 | 95 | org.springframework 96 | spring-core 97 | 98 | 99 | 100 | 101 | org.hibernate 102 | hibernate-validator 103 | 104 | 105 | 106 | commons-lang 107 | commons-lang 108 | 109 | 110 | 111 | com.google.code.gson 112 | gson 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/Rest.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core; 2 | 3 | /** 4 | * 相应消息对象 5 | * Created by Gaojun.Zhou 2017年6月8日 6 | */ 7 | 8 | public class Rest { 9 | 10 | private int code; 11 | 12 | private boolean success; 13 | 14 | private String message; 15 | 16 | private Object data; 17 | 18 | private String details; 19 | 20 | public int getCode() { 21 | return code; 22 | } 23 | 24 | public void setCode(int code) { 25 | this.code = code; 26 | } 27 | 28 | public boolean isSuccess() { 29 | return success; 30 | } 31 | 32 | public void setSuccess(boolean success) { 33 | this.success = success; 34 | } 35 | 36 | public String getMessage() { 37 | return message; 38 | } 39 | 40 | public void setMessage(String message) { 41 | this.message = message; 42 | } 43 | 44 | public Object getData() { 45 | return data; 46 | } 47 | 48 | public void setData(Object data) { 49 | this.data = data; 50 | } 51 | 52 | public String getDetails() { 53 | return details; 54 | } 55 | 56 | public void setDetails(String details) { 57 | this.details = details; 58 | } 59 | 60 | public Rest(int code, boolean success, String message, Object data, String details) { 61 | super(); 62 | this.code = code; 63 | this.success = success; 64 | this.message = message; 65 | this.data = data; 66 | this.details = details; 67 | } 68 | 69 | public static Rest ok(){ 70 | return new Rest(200,true,"ok",null,null); 71 | } 72 | 73 | public static Rest ok(String message){ 74 | return new Rest(200,true,message,null,null); 75 | } 76 | 77 | public static Rest okData(Object object){ 78 | return new Rest(200,true,"ok",object,null); 79 | } 80 | 81 | public static Rest failure(String message){ 82 | return new Rest(500,false,message,null,null); 83 | } 84 | 85 | public static Rest failure(int code,String message,Object object,String details){ 86 | return new Rest(code,false,message,object,details); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/advice/ExceptionAdvice.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.advice; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.validation.ValidationException; 5 | 6 | import org.apache.log4j.Logger; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.converter.HttpMessageNotReadableException; 9 | import org.springframework.web.HttpMediaTypeNotSupportedException; 10 | import org.springframework.web.HttpRequestMethodNotSupportedException; 11 | import org.springframework.web.bind.annotation.ExceptionHandler; 12 | import org.springframework.web.bind.annotation.ResponseStatus; 13 | import org.springframework.web.servlet.NoHandlerFoundException; 14 | 15 | import com.restful.api.core.Rest; 16 | import com.restful.api.core.ex.NotFindDataException; 17 | 18 | /** 19 | * 全局异常处理器 20 | * Created by Gaojun.Zhou 2017年6月8日 21 | */ 22 | public class ExceptionAdvice { 23 | 24 | public static final Logger logger = Logger.getLogger(ExceptionAdvice.class); 25 | 26 | /** 27 | * 400 - Bad Request 28 | */ 29 | @ResponseStatus(HttpStatus.BAD_REQUEST) 30 | @ExceptionHandler(ValidationException.class) 31 | public Rest handleValidationException(ValidationException e) { 32 | logger.error("参数验证失败", e); 33 | return Rest.failure(400,"参数验证失败",null,e.getMessage()); 34 | } 35 | /** 36 | * 400 - Bad Request 37 | */ 38 | @ResponseStatus(HttpStatus.BAD_REQUEST) 39 | @ExceptionHandler(HttpMessageNotReadableException.class) 40 | public Rest handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { 41 | logger.error("参数解析失败", e); 42 | return Rest.failure(400,"参数解析失败",null,e.getMessage()); 43 | } 44 | 45 | /** 46 | * 405 - Method Not Allowed 47 | */ 48 | @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) 49 | @ExceptionHandler(HttpRequestMethodNotSupportedException.class) 50 | public Rest handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e,HttpServletRequest request) { 51 | logger.error("不支持当前请求方法", e); 52 | return Rest.failure(405,String.format("不支持%s请求方式",request.getMethod()),null,e.getMessage()); 53 | } 54 | 55 | /** 56 | * 415 - Unsupported Media Type 57 | */ 58 | @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) 59 | @ExceptionHandler(HttpMediaTypeNotSupportedException.class) 60 | public Rest handleHttpMediaTypeNotSupportedException(Exception e) { 61 | logger.error("不支持当前媒体类型", e); 62 | return Rest.failure(415,"不支持当前媒体类型",null,e.getMessage()); 63 | } 64 | 65 | /** 66 | * 404 - Not Found 67 | */ 68 | @ResponseStatus(HttpStatus.NOT_FOUND) 69 | @ExceptionHandler(NoHandlerFoundException.class) 70 | public Rest handleNoHandlerFoundException(NoHandlerFoundException e) { 71 | logger.error("资源不存在", e); 72 | return Rest.failure(404,"资源不存在",null,e.getMessage()); 73 | } 74 | 75 | /** 76 | * 500 - NullPointerException Server Error 77 | */ 78 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 79 | @ExceptionHandler(NullPointerException.class) 80 | public Rest handleNullPointerException(NullPointerException e) { 81 | logger.error("空指针异常", e); 82 | return Rest.failure(500,"空指针异常",null,e.getMessage()); 83 | } 84 | /** 85 | * 604 - NullPointerException Server Error 86 | */ 87 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 88 | @ExceptionHandler(NotFindDataException.class) 89 | public Rest handleNotFindDataException(NotFindDataException e) { 90 | logger.error("未查到数据", e); 91 | return Rest.failure(e.getCode(),e.getMessage(),null,e.getClass().getName()); 92 | } 93 | /** 94 | * 500 - Internal Server Error 95 | */ 96 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 97 | @ExceptionHandler(Exception.class) 98 | public Rest handleException(Exception e) { 99 | logger.error("服务运行异常,"+e.getMessage(), e); 100 | return Rest.failure(500,e.getMessage(),null,e.getClass().getName()); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/advice/ForbidMethodAdvice.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.advice; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import org.apache.commons.lang.ArrayUtils; 6 | import org.apache.log4j.Logger; 7 | import org.aspectj.lang.JoinPoint; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.annotation.Before; 10 | import org.aspectj.lang.annotation.Pointcut; 11 | import org.aspectj.lang.reflect.MethodSignature; 12 | import org.springframework.stereotype.Component; 13 | 14 | import com.restful.api.core.anno.ForbidMethod; 15 | import com.restful.api.core.ex.ForbidAccessException; 16 | /** 17 | * 禁止指定方法访问 18 | * Created by Gaojun.Zhou 2017年6月21日 19 | */ 20 | @Aspect 21 | @Component 22 | public class ForbidMethodAdvice { 23 | 24 | public static final Logger logger = Logger.getLogger(ForbidMethodAdvice.class); 25 | 26 | @Pointcut("this(com.restful.api.core.controller.CrudController)") 27 | public void controllerAspect() { 28 | 29 | } 30 | /** 31 | * 当方法开始执行之前执行 32 | * @param joinPoint 33 | */ 34 | @Before("controllerAspect()") 35 | public void doBefore(JoinPoint joinPoint) { 36 | 37 | MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); 38 | Method method = methodSignature.getMethod(); 39 | 40 | String name = method.getName(); //方法名称 41 | Object ctr = joinPoint.getTarget(); //当前控制器 42 | 43 | logger.debug("methodName : " + name + ", ctr : " + ctr); 44 | 45 | ForbidMethod forbidMethodAnno = joinPoint.getTarget().getClass().getAnnotation(ForbidMethod.class); 46 | if(forbidMethodAnno!=null){ 47 | String[] value = forbidMethodAnno.value(); 48 | if(ArrayUtils.contains(value, name)){ 49 | throw new ForbidAccessException(name+"禁止访问"); 50 | } 51 | } 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/anno/ForbidMethod.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.anno; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 禁止访问方法注解,标注在Controller上 11 | * Created by Gaojun.Zhou 2017年6月9日 12 | */ 13 | @Target(ElementType.TYPE) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Documented 16 | public @interface ForbidMethod { 17 | 18 | String[] value() default {}; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/anno/Log.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.anno; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 记录业务日志 11 | * @author Administrator 12 | * 13 | */ 14 | @Target(ElementType.METHOD) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Documented 17 | public @interface Log { 18 | /** 19 | * 日志标题 20 | * @return 21 | */ 22 | String title() default ""; 23 | /** 24 | * 日志内容 25 | * @return 26 | */ 27 | String value() default ""; 28 | } 29 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/controller/AppController.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.controller; 2 | 3 | import java.io.Serializable; 4 | 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | 8 | import com.baomidou.mybatisplus.plugins.Page; 9 | import com.baomidou.mybatisplus.service.IService; 10 | import com.restful.api.core.Rest; 11 | import com.restful.api.core.ex.NotFindDataException; 12 | 13 | /** 14 | * Rest 风格之外的公共扩展接口 15 | * Created by Gaojun.Zhou 2017年6月8日 16 | */ 17 | public abstract class AppController> extends CrudController{ 18 | 19 | /** 20 | * 分页查询对象 21 | * @param page 22 | * @param size 23 | * @return 24 | */ 25 | @GetMapping("/page") 26 | public Rest page( 27 | @RequestParam (required = true,defaultValue="1") Integer page, 28 | @RequestParam (defaultValue="10")Integer size){ 29 | 30 | Page pageData = getS().selectPage(new Page(page, size)); 31 | if(pageData != null && pageData.getTotal() !=0){ 32 | return Rest.okData(pageData); 33 | } 34 | 35 | throw new NotFindDataException("未查询到任何数据"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/controller/CrudController.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.controller; 2 | 3 | import java.io.Serializable; 4 | import java.util.List; 5 | 6 | import javax.validation.Valid; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.validation.BindingResult; 11 | import org.springframework.web.bind.annotation.DeleteMapping; 12 | import org.springframework.web.bind.annotation.GetMapping; 13 | import org.springframework.web.bind.annotation.PathVariable; 14 | import org.springframework.web.bind.annotation.PostMapping; 15 | import org.springframework.web.bind.annotation.PutMapping; 16 | 17 | import com.baomidou.mybatisplus.service.IService; 18 | import com.restful.api.core.Rest; 19 | import com.restful.api.core.ex.NotFindDataException; 20 | import com.restful.api.core.util.ValidateUtil; 21 | 22 | /** 23 | * Rest CRUD 超级控制器,目的在于所有继承该控制器的子控制器自带标准的5个Rest接口,包含CRUD 24 | * Created by Gaojun.Zhou 2017年6月8日 25 | * 26 | * T 表示要操作的实体,实现序列化接口Serializable 27 | * S 表示调用对象的服务层接口,一班情况下要求存在 28 | * 29 | */ 30 | public abstract class CrudController> { 31 | 32 | /** 33 | * 注入服务层 34 | */ 35 | @Autowired(required = false) private S s; 36 | 37 | public S getS() { 38 | return s; 39 | } 40 | 41 | /** 42 | * 43 | * @return 44 | */ 45 | @GetMapping 46 | public Rest list(){ 47 | List list = s.selectList(null); //查询所有对象,null表示没有条件,会返回所有对象,Mybatis-Plus的特性 48 | if(!list.isEmpty()){ 49 | return Rest.okData(list); 50 | } 51 | throw new NotFindDataException("未查询到任何对象"); 52 | 53 | } 54 | 55 | @GetMapping("/{id}") 56 | public Rest get(@PathVariable("id") Serializable id){ 57 | 58 | if(id==null){ 59 | throw new RuntimeException("参数{id}不能为空"); 60 | } 61 | if(id instanceof String){ 62 | if(StringUtils.isBlank((String)id)){ 63 | throw new RuntimeException("参数{id}不能为空"); 64 | } 65 | } 66 | T t = s.selectById(id); 67 | if(t != null){ 68 | return Rest.okData(t); 69 | } 70 | throw new NotFindDataException(String.format("id为[%s]的对象不存在",id)); 71 | } 72 | 73 | /** 74 | * 创建对象 75 | * @param t 76 | * @param result 验证器,和Mode层配合使用 77 | * @return 78 | */ 79 | @PostMapping 80 | public Rest add(@Valid T t,BindingResult result){ 81 | 82 | if(result.hasErrors()){ 83 | return Rest.failure(500,"参数验证失败",ValidateUtil.toStringJson(result),"error"); 84 | } 85 | s.insert(t); 86 | return Rest.ok(); 87 | } 88 | 89 | @PutMapping 90 | public Rest update(@Valid T t,BindingResult result){ 91 | if(result.hasErrors()){ 92 | return Rest.failure(500,"参数验证失败",ValidateUtil.toStringJson(result),"error"); 93 | } 94 | s.updateById(t); 95 | return Rest.ok(); 96 | } 97 | 98 | /** 99 | * 删除对象 100 | * @param id 101 | * @return 102 | */ 103 | @DeleteMapping("/{id}") 104 | public Rest delete(@PathVariable("id") Serializable id){ 105 | 106 | if(id==null){ 107 | throw new RuntimeException("参数{id}不能为空"); 108 | } 109 | if(id instanceof String){ 110 | if(StringUtils.isBlank((String)id)){ 111 | throw new RuntimeException("参数{id}不能为空"); 112 | } 113 | } 114 | T t = s.selectById(id); 115 | if(t== null){ 116 | throw new NotFindDataException("要删除的对象不存在"); 117 | }else if(s.deleteById(id)){ 118 | return Rest.ok("删除成功"); 119 | }else{ 120 | throw new RuntimeException("糟糕,删除失败"); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/ex/ForbidAccessException.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.ex; 2 | 3 | /** 4 | * 禁止访问异常 5 | * Created by Gaojun.Zhou 2017年6月8日 6 | */ 7 | public class ForbidAccessException extends RuntimeException{ 8 | 9 | private static final long serialVersionUID = 1L; 10 | 11 | public ForbidAccessException() { 12 | super(); 13 | // TODO Auto-generated constructor stub 14 | } 15 | 16 | public ForbidAccessException(String message, Throwable cause, boolean enableSuppression, 17 | boolean writableStackTrace) { 18 | super(message, cause, enableSuppression, writableStackTrace); 19 | // TODO Auto-generated constructor stub 20 | } 21 | 22 | public ForbidAccessException(String message, Throwable cause) { 23 | super(message, cause); 24 | // TODO Auto-generated constructor stub 25 | } 26 | 27 | public ForbidAccessException(String message) { 28 | super(message); 29 | // TODO Auto-generated constructor stub 30 | } 31 | 32 | public ForbidAccessException(Throwable cause) { 33 | super(cause); 34 | // TODO Auto-generated constructor stub 35 | } 36 | 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/ex/NotFindDataException.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.ex; 2 | 3 | /** 4 | * 未查到数据异常 5 | * Created by Gaojun.Zhou 2017年6月8日 6 | */ 7 | public class NotFindDataException extends RuntimeException{ 8 | 9 | private int code = 604 ; 10 | 11 | 12 | public int getCode() { 13 | return code; 14 | } 15 | 16 | public void setCode(int code) { 17 | this.code = code; 18 | } 19 | 20 | /** 21 | * 22 | */ 23 | private static final long serialVersionUID = 1L; 24 | 25 | public NotFindDataException() { 26 | super(); 27 | // TODO Auto-generated constructor stub 28 | } 29 | 30 | public NotFindDataException(String message, Throwable cause, boolean enableSuppression, 31 | boolean writableStackTrace) { 32 | super(message, cause, enableSuppression, writableStackTrace); 33 | // TODO Auto-generated constructor stub 34 | } 35 | 36 | public NotFindDataException(String message, Throwable cause) { 37 | super(message, cause); 38 | // TODO Auto-generated constructor stub 39 | } 40 | 41 | public NotFindDataException(String message) { 42 | super(message); 43 | // TODO Auto-generated constructor stub 44 | } 45 | 46 | public NotFindDataException(Throwable cause) { 47 | super(cause); 48 | // TODO Auto-generated constructor stub 49 | } 50 | 51 | 52 | 53 | } 54 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/jackson/CustomObjectMapper.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.jackson; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | 6 | import org.springframework.util.StringUtils; 7 | 8 | import com.fasterxml.jackson.annotation.JsonInclude; 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | import com.fasterxml.jackson.databind.PropertyNamingStrategy; 11 | import com.fasterxml.jackson.databind.SerializationFeature; 12 | 13 | /** 14 | * Json转换配置 15 | * @author Administrator 16 | * 17 | */ 18 | public class CustomObjectMapper extends ObjectMapper { 19 | 20 | /** 21 | * 22 | */ 23 | private static final long serialVersionUID = 1L; 24 | 25 | private boolean camelCaseToLowerCaseWithUnderscores = false; 26 | private String dateFormatPattern; 27 | 28 | public void setCamelCaseToLowerCaseWithUnderscores( 29 | boolean camelCaseToLowerCaseWithUnderscores) { 30 | this.camelCaseToLowerCaseWithUnderscores = camelCaseToLowerCaseWithUnderscores; 31 | } 32 | 33 | public void setDateFormatPattern(String dateFormatPattern) { 34 | this.dateFormatPattern = dateFormatPattern; 35 | } 36 | 37 | public void init() { 38 | // 排除值为空属性 39 | setSerializationInclusion(JsonInclude.Include.NON_NULL); 40 | // 进行缩进输出 41 | configure(SerializationFeature.INDENT_OUTPUT, true); 42 | // 将驼峰转为下划线 43 | if (camelCaseToLowerCaseWithUnderscores) { 44 | setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); 45 | } 46 | // 进行日期格式化 47 | if (!StringUtils.isEmpty(dateFormatPattern)) { 48 | DateFormat dateFormat = new SimpleDateFormat(dateFormatPattern); 49 | setDateFormat(dateFormat); 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/jsonp/JsonpSupportAdvice.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.jsonp; 2 | import org.springframework.web.bind.annotation.ControllerAdvice; 3 | import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; 4 | /** 5 | * JSONP支持 6 | * @author Administrator 7 | * 8 | */ 9 | @ControllerAdvice 10 | public class JsonpSupportAdvice extends AbstractJsonpResponseBodyAdvice { 11 | public JsonpSupportAdvice() { 12 | //参数包含callback的时候 使用jsonp返回数据 13 | super("callback"); 14 | } 15 | } -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/log/LogAdvice.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.log; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.Date; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | import org.apache.log4j.Logger; 9 | import org.aspectj.lang.JoinPoint; 10 | import org.aspectj.lang.annotation.AfterReturning; 11 | import org.aspectj.lang.annotation.Aspect; 12 | import org.aspectj.lang.annotation.Pointcut; 13 | import org.aspectj.lang.reflect.MethodSignature; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.web.context.request.RequestContextHolder; 17 | import org.springframework.web.context.request.ServletRequestAttributes; 18 | 19 | import com.google.gson.Gson; 20 | import com.restful.api.core.anno.Log; 21 | import com.restful.api.core.util.IpUtil; 22 | /** 23 | * 正常业务日志记录 24 | * @author Administrator 25 | * 26 | */ 27 | @Aspect 28 | @Component 29 | public class LogAdvice { 30 | 31 | public static final Logger logger = Logger.getLogger(LogAdvice.class); 32 | 33 | /** 34 | * 注入日志记录接口,若存在则记录日志,不存在就忽略 35 | */ 36 | @Autowired(required=false) LogApi logApi; 37 | 38 | @Pointcut("@annotation(com.restful.api.core.anno.Log)") 39 | public void controllerAspect() { 40 | 41 | } 42 | /** 43 | * 当方法正常返回是执行 44 | * @param joinPoint 45 | */ 46 | @AfterReturning("controllerAspect()") 47 | public void doBefore(JoinPoint joinPoint) { 48 | 49 | MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); 50 | Method method = methodSignature.getMethod(); 51 | Log log = method.getAnnotation(Log.class); 52 | if(log != null){ 53 | String logTitle = log.title(); 54 | String logContent = log.value(); 55 | logger.debug("logs:[logTitle:"+logTitle+"][logContent:"+logContent+"]"); 56 | if(logApi != null){ 57 | HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 58 | LogBean logBean = new LogBean(); 59 | logBean.setLogTitle(logTitle); 60 | logBean.setLogTime(new Date()); 61 | logBean.setLogContent(logContent); 62 | logBean.setRequestMethod(request.getMethod()); 63 | logBean.setClientIp(IpUtil.getIpAddr(request)); 64 | logBean.setRequestParams(new Gson().toJson(request.getParameterMap())); 65 | logger.debug("logBean:"+logBean.toString()); 66 | logApi.log(logBean); 67 | }else{ 68 | logger.warn("LogApi not finish."); 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/log/LogApi.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.log; 2 | 3 | /** 4 | * 记录日志接口 5 | * Created by Gaojun.Zhou 2017年6月20日 6 | */ 7 | public interface LogApi { 8 | 9 | /** 10 | * 记录日志 11 | * @param log 12 | */ 13 | void log(LogBean log); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/log/LogBean.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.log; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * 日志对象 7 | * Created by Gaojun.Zhou 2017年6月20日 8 | */ 9 | public class LogBean { 10 | 11 | /** 12 | * 日志标题 13 | */ 14 | private String logTitle; 15 | /** 16 | * 日志内容 17 | */ 18 | private String logContent; 19 | /** 20 | * 客户端IP 21 | */ 22 | private String clientIp; 23 | /** 24 | * 日志时间 25 | */ 26 | private Date logTime; 27 | /** 28 | * 请求方法 29 | */ 30 | private String requestMethod; 31 | /** 32 | * 请求参数 33 | */ 34 | private String requestParams; 35 | 36 | /** 37 | * 其他数据 38 | */ 39 | private String other; 40 | 41 | public String getLogTitle() { 42 | return logTitle; 43 | } 44 | 45 | public void setLogTitle(String logTitle) { 46 | this.logTitle = logTitle; 47 | } 48 | 49 | public String getLogContent() { 50 | return logContent; 51 | } 52 | 53 | public void setLogContent(String logContent) { 54 | this.logContent = logContent; 55 | } 56 | 57 | public String getClientIp() { 58 | return clientIp; 59 | } 60 | 61 | public void setClientIp(String clientIp) { 62 | this.clientIp = clientIp; 63 | } 64 | 65 | public Date getLogTime() { 66 | return logTime; 67 | } 68 | 69 | public void setLogTime(Date logTime) { 70 | this.logTime = logTime; 71 | } 72 | 73 | 74 | public String getRequestParams() { 75 | return requestParams; 76 | } 77 | 78 | public void setRequestParams(String requestParams) { 79 | this.requestParams = requestParams; 80 | } 81 | 82 | public String getRequestMethod() { 83 | return requestMethod; 84 | } 85 | 86 | public void setRequestMethod(String requestMethod) { 87 | this.requestMethod = requestMethod; 88 | } 89 | 90 | public String getOther() { 91 | return other; 92 | } 93 | 94 | public void setOther(String other) { 95 | this.other = other; 96 | } 97 | 98 | @Override 99 | public String toString() { 100 | return "LogBean [logTitle=" + logTitle + ", logContent=" + logContent + ", clientIp=" + clientIp + ", logTime=" 101 | + logTime + ", requestMethod=" + requestMethod + ", requestParams=" + requestParams + ", other=" + other 102 | + "]"; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/util/IpUtil.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.util; 2 | 3 | import java.net.InetAddress; 4 | import java.net.UnknownHostException; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | import org.apache.log4j.Logger; 9 | 10 | /** 11 | * IP工具类 12 | * Created by Gaojun.Zhou 2017年6月22日 13 | */ 14 | public class IpUtil { 15 | 16 | 17 | private static final Logger logger = Logger.getLogger("IpHelper"); 18 | 19 | private static String LOCAL_IP_STAR_STR = "192.168."; 20 | 21 | static { 22 | String ip = null; 23 | String hostName = null; 24 | try { 25 | hostName = InetAddress.getLocalHost().getHostName(); 26 | InetAddress ipAddr[] = InetAddress.getAllByName(hostName); 27 | for (int i = 0; i < ipAddr.length; i++) { 28 | ip = ipAddr[i].getHostAddress(); 29 | if (ip.startsWith(LOCAL_IP_STAR_STR)) { 30 | break; 31 | } 32 | } 33 | if (ip == null) { 34 | ip = ipAddr[0].getHostAddress(); 35 | } 36 | 37 | } catch (UnknownHostException e) { 38 | logger.error("IpHelper error."); 39 | e.printStackTrace(); 40 | } 41 | 42 | LOCAL_IP = ip; 43 | HOST_NAME = hostName; 44 | 45 | } 46 | 47 | /** 系统的本地IP地址 */ 48 | public static final String LOCAL_IP; 49 | 50 | /** 系统的本地服务器名 */ 51 | public static final String HOST_NAME; 52 | 53 | /** 54 | *

55 | * 获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。 56 | * 但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了,如果通过了多级反向代理的话, 57 | * X-Forwarded-For的值并不止一个,而是一串IP值, 究竟哪个才是真正的用户端的真实IP呢? 58 | * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 59 | * 例如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 60 | * 192.168.1.130, 192.168.1.100 用户真实IP为: 192.168.1.110 61 | *

62 | * 63 | * @param request 64 | * @return 65 | */ 66 | public static String getIpAddr(HttpServletRequest request) { 67 | String ip = request.getHeader("x-forwarded-for"); 68 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 69 | ip = request.getHeader("Proxy-Client-IP"); 70 | } 71 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 72 | ip = request.getHeader("WL-Proxy-Client-IP"); 73 | } 74 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 75 | ip = request.getRemoteAddr(); 76 | if (ip.equals("127.0.0.1")) { 77 | /** 根据网卡取本机配置的IP */ 78 | InetAddress inet = null; 79 | try { 80 | inet = InetAddress.getLocalHost(); 81 | ip = inet.getHostAddress(); 82 | } catch (UnknownHostException e) { 83 | logger.error("IpHelper error." + e.toString()); 84 | } 85 | } 86 | } 87 | /** 88 | * 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割 "***.***.***.***".length() = 89 | * 15 90 | */ 91 | if (ip != null && ip.length() > 15) { 92 | if (ip.indexOf(",") > 0) { 93 | ip = ip.substring(0, ip.indexOf(",")); 94 | } 95 | } 96 | return ip; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /restful-api-core/src/main/java/com/restful/api/core/util/ValidateUtil.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.core.util; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.validation.BindingResult; 7 | import org.springframework.validation.FieldError; 8 | 9 | /** 10 | * 验证工具类 11 | * Created by Gaojun.Zhou 2017年6月22日 12 | */ 13 | public class ValidateUtil { 14 | 15 | public static Map toStringJson(BindingResult result){ 16 | 17 | Map map = new HashMap(); 18 | 19 | for(FieldError fieldError : result.getFieldErrors()){ 20 | map.put(fieldError.getField(), fieldError.getDefaultMessage()); 21 | } 22 | 23 | return map; 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /restful-api-web/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.vaco 8 | restful-api 9 | 0.0.1-SNAPSHOT 10 | 11 | restful-api-web 12 | war 13 | restful-api-web Maven Webapp 14 | http://maven.apache.org 15 | 16 | 17 | 18 | com.vaco 19 | restful-api-core 20 | 0.0.1-SNAPSHOT 21 | 22 | 23 | 24 | 25 | io.springfox 26 | springfox-swagger2 27 | 28 | 29 | io.springfox 30 | springfox-swagger-ui 31 | 32 | 33 | com.fasterxml 34 | classmate 35 | 36 | 37 | 38 | 39 | org.apache.velocity 40 | velocity 41 | 1.7 42 | test 43 | 44 | 45 | 46 | 47 | restful-api-web 48 | 49 | 50 | 51 | 52 | src/main/java 53 | 54 | **/*.xml 55 | 56 | false 57 | 58 | 59 | 60 | 61 | 62 | org.mortbay.jetty 63 | jetty-maven-plugin 64 | 8.1.16.v20140903 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/component/RestExceptionAdvice.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.component; 2 | 3 | import org.springframework.web.bind.annotation.ControllerAdvice; 4 | import org.springframework.web.bind.annotation.ResponseBody; 5 | 6 | import com.restful.api.core.advice.ExceptionAdvice; 7 | 8 | /** 9 | * 全局异常处理 10 | * Created by Gaojun.Zhou 2017年6月20日 11 | */ 12 | @ControllerAdvice 13 | @ResponseBody 14 | public class RestExceptionAdvice extends ExceptionAdvice{ 15 | 16 | } 17 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/component/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.component; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.service.ApiInfo; 9 | import springfox.documentation.service.Contact; 10 | import springfox.documentation.spi.DocumentationType; 11 | import springfox.documentation.spring.web.plugins.Docket; 12 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 13 | 14 | /** 15 | * swagger-ui配置 16 | * Created by Gaojun.Zhou 2017年6月19日 17 | */ 18 | @EnableSwagger2 19 | @Configuration 20 | public class SwaggerConfig { 21 | 22 | @Bean 23 | public Docket createRestApi() { 24 | return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() 25 | //.apis(RequestHandlerSelectors.basePackage("com.vacomall.controller")) 26 | .paths(PathSelectors.any()) 27 | .build(); 28 | } 29 | 30 | private ApiInfo apiInfo() { 31 | return new ApiInfoBuilder().title("restful-api,Restfull接口生成框架") 32 | .termsOfServiceUrl("http://blog.jdoop.cn/") 33 | .description("springmvc + swagger2 Restfull接口生成框架") 34 | .contact(new Contact("JamesZhou", "http://blog.jdoop.cn/", "gaojun.zhou@qq.com")) 35 | .version("1.0.0") 36 | .build(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/controller/BlogController.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.controller; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestParam; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import com.baomidou.mybatisplus.plugins.Page; 11 | import com.restful.api.core.Rest; 12 | import com.restful.api.core.anno.ForbidMethod; 13 | import com.restful.api.core.anno.Log; 14 | import com.restful.api.core.controller.AppController; 15 | import com.restful.api.web.entity.Blog; 16 | import com.restful.api.web.service.IBlogService; 17 | /** 18 | * 标准的Rest接口,实例控制器 19 | * Created by Gaojun.Zhou 2017年6月8日 20 | */ 21 | @RestController 22 | @RequestMapping("/blog") 23 | @ForbidMethod({"delete"}) //禁止客户端调用delete方法,可穿入多个参数 24 | public class BlogController extends AppController{ 25 | 26 | /** 27 | * 自定义方法分页多表连接查询博客 28 | */ 29 | @GetMapping("/findJoinPage") 30 | public Rest findJoinPage(@RequestParam (required = true,defaultValue="1") 31 | Integer page,@RequestParam (defaultValue="10")Integer size){ 32 | Page> pageData = getS().selectBlogPage(new Page>(page,size)); 33 | return Rest.okData(pageData); 34 | 35 | } 36 | 37 | /** 38 | * 记录日志测试 39 | * @see @Log 记录日志只在方法执行成功返回后执行,通过 com.restful.api.core.log.LogAdvice AOP实现 40 | * @see 开发者可实现 LogApi接口的log方法完成记录日志具体的业务,此项目中完善service下的LogServiceImpl.java的log方法即可 41 | * @return rest 42 | */ 43 | @GetMapping("/testLog") 44 | @Log(title="测试日志",value="这是日志内容,哈哈") 45 | public Rest testLog(){ 46 | return Rest.ok(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/entity/Blog.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import org.hibernate.validator.constraints.NotBlank; 7 | 8 | import com.baomidou.mybatisplus.annotations.TableField; 9 | import com.baomidou.mybatisplus.annotations.TableId; 10 | import com.baomidou.mybatisplus.annotations.TableName; 11 | import com.baomidou.mybatisplus.enums.IdType; 12 | 13 | import io.swagger.annotations.ApiModelProperty; 14 | 15 | /** 16 | * 17 | * 博客 18 | * 19 | */ 20 | @TableName("tb_blog") 21 | public class Blog implements Serializable { 22 | 23 | @TableField(exist = false) 24 | private static final long serialVersionUID = 1L; 25 | 26 | /** 主键 */ 27 | @TableId(type = IdType.UUID) 28 | @ApiModelProperty(value = "id",hidden=true) 29 | private String id; 30 | /** 31 | * 标题 32 | */ 33 | @NotBlank(message="文章标题不能为空") 34 | private String title; 35 | /** 36 | * 内容 37 | */ 38 | @NotBlank(message="文章内容不能为空") 39 | private String content; 40 | /** 41 | * 创建时间 42 | */ 43 | private Date createTime; 44 | /** 45 | * 用户ID 46 | */ 47 | @ApiModelProperty(hidden=true) 48 | private String userId; 49 | 50 | public String getId() { 51 | return id; 52 | } 53 | 54 | public void setId(String id) { 55 | this.id = id; 56 | } 57 | 58 | public String getTitle() { 59 | return title; 60 | } 61 | 62 | public void setTitle(String title) { 63 | this.title = title; 64 | } 65 | 66 | public String getContent() { 67 | return content; 68 | } 69 | 70 | public void setContent(String content) { 71 | this.content = content; 72 | } 73 | 74 | public Date getCreateTime() { 75 | return createTime; 76 | } 77 | 78 | public void setCreateTime(Date createTime) { 79 | this.createTime = createTime; 80 | } 81 | 82 | public String getUserId() { 83 | return userId; 84 | } 85 | 86 | public void setUserId(String userId) { 87 | this.userId = userId; 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.validation.constraints.Pattern; 7 | 8 | import org.hibernate.validator.constraints.Length; 9 | import org.hibernate.validator.constraints.NotBlank; 10 | import org.hibernate.validator.constraints.NotEmpty; 11 | 12 | import com.baomidou.mybatisplus.annotations.TableField; 13 | import com.baomidou.mybatisplus.annotations.TableId; 14 | import com.baomidou.mybatisplus.annotations.TableName; 15 | import com.baomidou.mybatisplus.enums.IdType; 16 | 17 | /** 18 | * 19 | * 20 | * 21 | */ 22 | @TableName("tb_user") 23 | public class User implements Serializable { 24 | 25 | @TableField(exist = false) 26 | private static final long serialVersionUID = 1L; 27 | 28 | /** 主键 */ 29 | @TableId(type = IdType.UUID) 30 | private String id; 31 | 32 | /** 用户名 */ 33 | @NotEmpty(message = "用户名不能为空") 34 | @Length(min = 5, max = 20, message = "用户名长度为5-20之间") 35 | @Pattern(regexp = "[a-zA-Z]{5,20}", message = "用户名不合法") 36 | private String userName; 37 | 38 | /** 密码 */ 39 | @NotBlank(message="密码不能为空") 40 | @Length(min = 5, max = 20, message = "密码长度为5-20之间") 41 | private String password; 42 | 43 | /** 创建时间 */ 44 | private Date createTime; 45 | 46 | /** 描述 */ 47 | private String userDesc; 48 | 49 | 50 | public String getId() { 51 | return this.id; 52 | } 53 | 54 | public void setId(String id) { 55 | this.id = id; 56 | } 57 | 58 | public String getUserName() { 59 | return this.userName; 60 | } 61 | 62 | public void setUserName(String userName) { 63 | this.userName = userName; 64 | } 65 | 66 | public String getPassword() { 67 | return this.password; 68 | } 69 | 70 | public void setPassword(String password) { 71 | this.password = password; 72 | } 73 | 74 | 75 | public Date getCreateTime() { 76 | return this.createTime; 77 | } 78 | 79 | public void setCreateTime(Date createTime) { 80 | this.createTime = createTime; 81 | } 82 | 83 | public String getUserDesc() { 84 | return this.userDesc; 85 | } 86 | 87 | public void setUserDesc(String userDesc) { 88 | this.userDesc = userDesc; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/mapper/BlogMapper.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.mapper; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.baomidou.mybatisplus.mapper.BaseMapper; 7 | import com.baomidou.mybatisplus.plugins.Page; 8 | import com.restful.api.web.entity.Blog; 9 | 10 | /** 11 | * 12 | * Blog 表数据库控制层接口 13 | * 14 | */ 15 | public interface BlogMapper extends BaseMapper { 16 | 17 | List> selectMap(Page> page); 18 | 19 | } -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.mapper; 2 | 3 | import com.restful.api.web.entity.User; 4 | import com.baomidou.mybatisplus.mapper.BaseMapper; 5 | 6 | /** 7 | *

8 | * Mapper 接口 9 | *

10 | * 11 | * @author GaoJun.Zhou 12 | * @since 2017-06-21 13 | */ 14 | public interface UserMapper extends BaseMapper { 15 | 16 | } -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/mapper/xml/BlogMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/mapper/xml/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/service/IBlogService.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.service; 2 | 3 | import java.util.Map; 4 | 5 | import com.baomidou.mybatisplus.plugins.Page; 6 | import com.baomidou.mybatisplus.service.IService; 7 | import com.restful.api.web.entity.Blog; 8 | 9 | /** 10 | * 11 | * Blog 表数据服务层接口 12 | * 13 | */ 14 | public interface IBlogService extends IService { 15 | 16 | Page> selectBlogPage(Page> page); 17 | 18 | 19 | } -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/service/IUserService.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.service; 2 | 3 | import com.restful.api.web.entity.User; 4 | import com.baomidou.mybatisplus.service.IService; 5 | 6 | /** 7 | *

8 | * 服务类 9 | *

10 | * 11 | * @author GaoJun.Zhou 12 | * @since 2017-06-21 13 | */ 14 | public interface IUserService extends IService { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/service/impl/BlogServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.service.impl; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.baomidou.mybatisplus.plugins.Page; 10 | import com.baomidou.mybatisplus.service.impl.ServiceImpl; 11 | import com.restful.api.web.entity.Blog; 12 | import com.restful.api.web.mapper.BlogMapper; 13 | import com.restful.api.web.service.IBlogService; 14 | 15 | /** 16 | * 17 | * Blog 表数据服务层接口实现类 18 | * 19 | */ 20 | @Service 21 | public class BlogServiceImpl extends ServiceImpl implements IBlogService { 22 | 23 | @Autowired private BlogMapper blogMapper; 24 | 25 | @Override 26 | public Page> selectBlogPage(Page> page) { 27 | // TODO Auto-generated method stub 28 | 29 | List> list = blogMapper.selectMap(page); 30 | page.setRecords(list); 31 | return page; 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/service/impl/LogServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.service.impl; 2 | 3 | import org.apache.log4j.Logger; 4 | import org.springframework.stereotype.Service; 5 | import org.springframework.transaction.annotation.Transactional; 6 | 7 | import com.restful.api.core.log.LogApi; 8 | import com.restful.api.core.log.LogBean; 9 | 10 | /** 11 | * 记录日志业务,开发这个实现LogApi接口的log方法可灵活处理日志,如记录在数据库 12 | * Created by Gaojun.Zhou 2017年6月20日 13 | */ 14 | @Service 15 | public class LogServiceImpl implements LogApi { 16 | 17 | public static final Logger logger = Logger.getLogger(LogServiceImpl.class); 18 | 19 | @Transactional 20 | @Override 21 | public void log(LogBean log) { 22 | // TODO Auto-generated method stub 23 | 24 | //这里实现记录日志的逻辑 25 | 26 | //logger.warn("logAdvice not finish,"+log.toString()); 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /restful-api-web/src/main/java/com/restful/api/web/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.restful.api.web.service.impl; 2 | 3 | import com.restful.api.web.entity.User; 4 | import com.restful.api.web.mapper.UserMapper; 5 | import com.restful.api.web.service.IUserService; 6 | import com.baomidou.mybatisplus.service.impl.ServiceImpl; 7 | import org.springframework.stereotype.Service; 8 | 9 | /** 10 | *

11 | * 服务实现类 12 | *

13 | * 14 | * @author GaoJun.Zhou 15 | * @since 2017-06-21 16 | */ 17 | @Service 18 | public class UserServiceImpl extends ServiceImpl implements IUserService { 19 | 20 | } 21 | -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=DEBUG,INFO,ERROR,Console 2 | log4j.logger.org.mybatis = INFO 3 | #Console 4 | log4j.appender.Console=org.apache.log4j.ConsoleAppender 5 | log4j.appender.Console.layout=org.apache.log4j.PatternLayout 6 | log4j.appender.Console.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%t] [%p] [%c.%M] [%L] - %m%n 7 | #RollingFile INFO 8 | log4j.appender.INFO=org.apache.log4j.DailyRollingFileAppender 9 | log4j.appender.INFO.layout=org.apache.log4j.PatternLayout 10 | log4j.appender.INFO.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%t] [%p] [%c.%M] [%L] - %m%n 11 | log4j.appender.INFO.Threshold=INFO 12 | log4j.appender.INFO.File=${root}/info.log 13 | #RollingFile2 ERROR 14 | log4j.appender.ERROR=org.apache.log4j.DailyRollingFileAppender 15 | log4j.appender.ERROR.layout=org.apache.log4j.PatternLayout 16 | log4j.appender.ERROR.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%t] [%p] [%c.%M] [%L] - %m%n 17 | log4j.appender.ERROR.Threshold=ERROR 18 | log4j.appender.ERROR.Append=true 19 | log4j.appender.ERROR.File=${root}/error.log 20 | root=D:/logs/restfull-web-api -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/properties/jdbc.properties: -------------------------------------------------------------------------------- 1 | jdbc.driver=com.mysql.jdbc.Driver 2 | jdbc.url=jdbc:mysql://127.0.0.1:3306/restful-api?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull 3 | jdbc.username=root 4 | jdbc.password=root 5 | validationQuery=SELECT 1 -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/spring/applicationContext-dao.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/spring/applicationContext-service.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/spring/servlet-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/sql/restful-api.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SQLyog Ultimate v11.24 (32 bit) 3 | MySQL - 5.5.44 : Database - restful-api 4 | ********************************************************************* 5 | */ 6 | 7 | /*!40101 SET NAMES utf8 */; 8 | 9 | /*!40101 SET SQL_MODE=''*/; 10 | 11 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 12 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 13 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 14 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 15 | CREATE DATABASE /*!32312 IF NOT EXISTS*/`restful-api` /*!40100 DEFAULT CHARACTER SET utf8 */; 16 | 17 | USE `restful-api`; 18 | 19 | /*Table structure for table `tb_blog` */ 20 | 21 | DROP TABLE IF EXISTS `tb_blog`; 22 | 23 | CREATE TABLE `tb_blog` ( 24 | `id` varchar(50) NOT NULL COMMENT '主键', 25 | `title` varchar(200) DEFAULT NULL COMMENT '标题', 26 | `content` varchar(500) DEFAULT NULL COMMENT '内容', 27 | `userId` varchar(50) DEFAULT NULL COMMENT '作者', 28 | `createTime` datetime DEFAULT NULL COMMENT '创建时间', 29 | PRIMARY KEY (`id`) 30 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 31 | 32 | /*Data for the table `tb_blog` */ 33 | 34 | insert into `tb_blog`(`id`,`title`,`content`,`userId`,`createTime`) values ('1c6732d554044385837ba956112a252a','呵呵','哈哈','uidxxx','2017-06-09 09:53:10'),('436bfa2df0fe4b65b126dec65b3efb34','测试','测试内容','09c63f873a9e472ca464accb61cd5e51','2016-12-30 11:16:31'),('45e3d28b04774f48b8be0206a90cffe8','机构和计划','发的','uidxxx','2017-06-20 11:45:51'),('52d47feaf7404c818255e5ae021eacab','测试','测试内容','09c63f873a9e472ca464accb61cd5e51','2016-12-30 11:16:18'),('5a8d876cfe164695b5543091f7a91629','呵呵','哈哈','uidxxx','2017-06-09 10:27:40'),('7177a02736ed4985b4fc74a356a7b96e','测试','测试内容','09c63f873a9e472ca464accb61cd5e51','2016-12-30 11:16:30'),('72142bfdfbb84bd793e9dd8e961f3518','测试','测试内容','09c63f873a9e472ca464accb61cd5e51','2016-12-30 11:16:21'),('8f2b518ffb9645dc8e36030fa6cd2181','更多发挥','广告费','uidxxx','2017-06-20 11:25:20'),('e975e62814d04264bf97793ca71609fb','呵呵','哈哈',NULL,'2017-06-09 09:52:36'); 35 | 36 | /*Table structure for table `tb_user` */ 37 | 38 | DROP TABLE IF EXISTS `tb_user`; 39 | 40 | CREATE TABLE `tb_user` ( 41 | `id` varchar(50) NOT NULL COMMENT '主键', 42 | `userName` varchar(50) NOT NULL COMMENT '用户名', 43 | `password` varchar(50) NOT NULL COMMENT '密码', 44 | `createTime` datetime DEFAULT NULL COMMENT '创建时间', 45 | `userDesc` varchar(300) DEFAULT NULL COMMENT '描述', 46 | PRIMARY KEY (`id`) 47 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 48 | 49 | /*Data for the table `tb_user` */ 50 | 51 | insert into `tb_user`(`id`,`userName`,`password`,`createTime`,`userDesc`) values ('09c63f873a9e472ca464accb61cd5e51','test','DC483E80A7A0BD9EF71D8CF973673924','2016-12-12 15:50:39','aaaaa'),('4754f010ef344c59b728ea60809ab926','e100000','1973EBD114AAB8BD85457E037BBBFA62','2016-12-12 13:43:59','aa44515112121'),('549d321508db446e9bcaa477835fe5f1','admin','E10ADC3949BA59ABBE56E057F20F883E','2016-12-14 14:35:08','所有权限'),('629ba7eb1d8944d2873ecfc6896288e7','zhangsan','25F9E794323B453885F5181F1B624D0B','2016-12-12 11:49:21','张三负责系统的委会和开发工作。'); 52 | 53 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 54 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 55 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 56 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 57 | -------------------------------------------------------------------------------- /restful-api-web/src/main/resources/xml/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 33 | 34 | -------------------------------------------------------------------------------- /restful-api-web/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | restful-api-web 4 | 5 | encodingFilter 6 | org.springframework.web.filter.CharacterEncodingFilter 7 | 8 | encoding 9 | UTF-8 10 | 11 | 12 | forceEncoding 13 | true 14 | 15 | 16 | 17 | encodingFilter 18 | /* 19 | 20 | 21 | contextConfigLocation 22 | classpath:spring/applicationContext-*.xml 23 | 24 | 25 | org.springframework.web.context.ContextLoaderListener 26 | 27 | 28 | org.springframework.web.context.request.RequestContextListener 29 | 30 | 31 | spring-mvc 32 | org.springframework.web.servlet.DispatcherServlet 33 | 34 | contextConfigLocation 35 | classpath:spring/servlet-context.xml 36 | 37 | 1 38 | 39 | 40 | spring-mvc 41 | / 42 | 43 | -------------------------------------------------------------------------------- /restful-api-web/src/test/java/com/gen/MysqlGenerator.java: -------------------------------------------------------------------------------- 1 | package com.gen; 2 | import com.baomidou.mybatisplus.generator.AutoGenerator; 3 | import com.baomidou.mybatisplus.generator.config.DataSourceConfig; 4 | import com.baomidou.mybatisplus.generator.config.GlobalConfig; 5 | import com.baomidou.mybatisplus.generator.config.PackageConfig; 6 | import com.baomidou.mybatisplus.generator.config.StrategyConfig; 7 | import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; 8 | import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; 9 | import com.baomidou.mybatisplus.generator.config.rules.DbType; 10 | import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; 11 | 12 | /** 13 | *

14 | * 代码生成器演示 15 | *

16 | * 17 | * @author hubin 18 | * @date 2016-12-01 19 | */ 20 | public class MysqlGenerator { 21 | 22 | /** 23 | *

24 | * MySQL 生成演示 25 | *

26 | */ 27 | public static void main(String[] args) { 28 | 29 | 30 | AutoGenerator mpg = new AutoGenerator(); 31 | 32 | // 全局配置 33 | GlobalConfig gc = new GlobalConfig(); 34 | gc.setOutputDir("G:/develop/code2/"); 35 | gc.setFileOverride(true); 36 | gc.setActiveRecord(true);// 开启 activeRecord 模式 37 | gc.setEnableCache(false);// XML 二级缓存 38 | gc.setBaseResultMap(true);// XML ResultMap 39 | gc.setBaseColumnList(false);// XML columList 40 | gc.setAuthor("GaoJun.Zhou"); 41 | 42 | // 自定义文件命名,注意 %s 会自动填充表实体属性! 43 | // gc.setMapperName("%sDao"); 44 | // gc.setXmlName("%sDao"); 45 | // gc.setServiceName("MP%sService"); 46 | // gc.setServiceImplName("%sServiceDiy"); 47 | // gc.setControllerName("%sAction"); 48 | mpg.setGlobalConfig(gc); 49 | // 数据源配置 50 | DataSourceConfig dsc = new DataSourceConfig(); 51 | dsc.setDbType(DbType.MYSQL); 52 | dsc.setTypeConvert(new MySqlTypeConvert(){ 53 | // 自定义数据库表字段类型转换【可选】 54 | @Override 55 | public DbColumnType processTypeConvert(String fieldType) { 56 | System.out.println("转换类型:" + fieldType); 57 | return super.processTypeConvert(fieldType); 58 | } 59 | }); 60 | /*dsc.setDriverName("com.mysql.jdbc.Driver"); 61 | dsc.setUsername("root"); 62 | dsc.setPassword("root"); 63 | dsc.setUrl("jdbc:mysql://127.0.0.1:3306/kangarooadmin?characterEncoding=utf8");*/ 64 | 65 | dsc.setDriverName("com.mysql.jdbc.Driver"); 66 | dsc.setUsername("root"); 67 | dsc.setPassword("root"); 68 | dsc.setUrl("jdbc:mysql://localhost:3306/restful-api?characterEncoding=utf8"); 69 | mpg.setDataSource(dsc); 70 | 71 | // 策略配置 72 | StrategyConfig strategy = new StrategyConfig(); 73 | // strategy.setCapitalMode(true);// 全局大写命名 74 | // strategy.setDbColumnUnderline(true);//全局下划线命名 75 | //strategy.setTablePrefix(new String[] { "bmd_", "mp_" });// 此处可以修改为您的表前缀 76 | strategy.setTablePrefix(new String[] { "tb_"});// 此处可以修改为您的表前缀 77 | strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 78 | strategy.setInclude(new String[] { "tb_user","tb_blog" }); // 需要生成的表 79 | // strategy.setExclude(new String[]{"test"}); // 排除生成的表 80 | // 字段名生成策略 81 | //strategy.setFieldNaming(NamingStrategy.nochange); 82 | // 自定义实体父类 83 | // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); 84 | // 自定义实体,公共字段 85 | // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); 86 | // 自定义 mapper 父类 87 | // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); 88 | // 自定义 service 父类 89 | // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); 90 | // 自定义 service 实现类父类 91 | // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); 92 | // 自定义 controller 父类 93 | strategy.setSuperControllerClass("com.restful.api.core.CrudController"); 94 | // 【实体】是否生成字段常量(默认 false) 95 | // public static final String ID = "test_id"; 96 | // strategy.setEntityColumnConstant(true); 97 | // 【实体】是否为构建者模型(默认 false) 98 | // public User setName(String name) {this.name = name; return this;} 99 | // strategy.setEntityBuliderModel(true); 100 | mpg.setStrategy(strategy); 101 | 102 | 103 | // 包配置 104 | PackageConfig pc = new PackageConfig(); 105 | pc.setModuleName("web"); 106 | pc.setParent("com.restful.api");// 自定义包路径 107 | //pc.setController("controller");// 这里是控制器包名,默认 web 108 | //pc.setEntity("entity"); 109 | mpg.setPackageInfo(pc); 110 | 111 | // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值 112 | /*InjectionConfig cfg = new InjectionConfig() { 113 | @Override 114 | public void initMap() { 115 | Map map = new HashMap(); 116 | map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); 117 | this.setMap(map); 118 | } 119 | }; 120 | List focList = new ArrayList(); 121 | focList.add(new FileOutConfig("/template/entity.java.vm") { 122 | @Override 123 | public String outputFile(TableInfo tableInfo) { 124 | // 自定义输入文件名称 125 | return "/develop/code/my_" + tableInfo.getEntityName() + ".java"; 126 | } 127 | }); 128 | cfg.setFileOutConfigList(focList); 129 | mpg.setCfg(cfg);*/ 130 | 131 | // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy 132 | // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置: 133 | // TemplateConfig tc = new TemplateConfig(); 134 | // tc.setController(""); 135 | // tc.setEntity(""); 136 | //tc.setMapper("..."); 137 | //tc.setXml("..."); 138 | // tc.setService("..."); 139 | // tc.setServiceImpl("..."); 140 | // mpg.setTemplate(tc); 141 | 142 | // 执行生成 143 | mpg.execute(); 144 | 145 | // 打印注入设置 146 | //System.err.println(mpg.getCfg().getMap().get("abc")); 147 | } 148 | 149 | } 150 | --------------------------------------------------------------------------------