還在爲寫swagger而煩惱嗎?還在爲忘記寫註釋而煩惱嗎?還在爲寫簡單的api接口而煩惱嗎?mybatis-dsc-generator完美集成lombok,swagger的代碼生成工具,讓你再也不爲繁瑣的註釋和簡單的接口實現而煩惱:entity集成,格式校驗,swagger; dao自動加@ mapper,service自動註釋和依賴; 控制器實現單表的增副改查,並實現swaggers的api文檔。java
2.1.0版本是未集成Mybatis-plus版本——源碼分支mastergit
<dependency> <groupId>com.github.flying-cattle</groupId> <artifactId>mybatis-dsc-generator</artifactId> <version>2.1.0.RELEASE</version> </dependency>
3.0.0版本是集成了Mybatis-plus版本——源碼分支mybatisPlusgithub
<dependency> <groupId>com.github.flying-cattle</groupId> <artifactId>mybatis-dsc-generator</artifactId> <version>3.0.0.RELEASE</version> </dependency>
CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID', `login_name` varchar(40) DEFAULT NULL COMMENT '登陸名', `password` varchar(100) NOT NULL COMMENT '祕密', `nickname` varchar(50) NOT NULL COMMENT '暱稱', `type` int(10) unsigned DEFAULT NULL COMMENT '類型', `state` int(10) unsigned NOT NULL DEFAULT '1' COMMENT '狀態:-1失敗,0等待,1成功', `note` varchar(255) DEFAULT NULL COMMENT '備註', `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', `update_uid` bigint(20) DEFAULT '0' COMMENT '修改人用戶ID', `login_ip` varchar(50) DEFAULT NULL COMMENT '登陸IP地址', `login_addr` varchar(100) DEFAULT NULL COMMENT '登陸地址', PRIMARY KEY (`id`), UNIQUE KEY `login_name` (`login_name`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
要求必須有表註釋,要求必須有主鍵爲id,全部字段必須有註釋(便於生成java註釋swagger等)。web
生成方法參考源碼中的:https://gitee.com/flying-cattle/mybatis-dsc-generator/blob/master/src/main/java/com/github/mybatis/fl/test/TestMain.javaspring
/** * @filename:Order 2018年7月5日 * @project deal-center V1.0 * Copyright(c) 2018 BianP Co. Ltd. * All right reserved. */ import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; /** * Copyright: Copyright (c) 2019 * * <p>說明: 用戶實體類</P> * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------------* * 2019年4月9日 BianPeng V1.0 initialize */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class User extends Model<User> { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) @ApiModelProperty(name = "id" , value = "用戶ID") private Long id; @ApiModelProperty(name = "loginName" , value = "登陸帳戶") private String loginName; @ApiModelProperty(name = "password" , value = "登陸密碼") private String password; @ApiModelProperty(name = "nickname" , value = "用戶暱稱") private String nickname; @ApiModelProperty(name = "type" , value = "用戶類型") private Integer type; @ApiModelProperty(name = "state" , value = "用戶狀態") private Integer state; @ApiModelProperty(name = "note" , value = "備註") private String note; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") @ApiModelProperty(name = "createTime" , value = "用戶建立時間") private Date createTime; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") @ApiModelProperty(name = "updateTime" , value = "修改時間") private Date updateTime; @ApiModelProperty(name = "updateUid" , value = "修改人用戶ID") private Long updateUid; @ApiModelProperty(name = "loginIp" , value = "登陸IP") private String loginIp; @ApiModelProperty(name = "loginIp" , value = "登陸地址") private String loginAddr; @Override protected Serializable pkVal() { return this.id; } }
DAOsql
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.xin.usercenter.entity.User; /** * Copyright: Copyright (c) 2019 * * <p>說明: 用戶數據訪問層</P> * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------------* * 2019年4月9日 BianPeng V1.0 initialize */ @Mapper public interface UserDao extends BaseMapper<User> { }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xin.usercenter.dao.UserDao"> <resultMap id="BaseResultMap" type="com.xin.usercenter.entity.User"> <id column="id" property="id" /> <id column="login_name" property="loginName" /> <id column="password" property="password" /> <id column="nickname" property="nickname" /> <id column="type" property="type" /> <id column="state" property="state" /> <id column="note" property="note" /> <id column="create_time" property="createTime" /> <id column="update_time" property="updateTime" /> <id column="update_uid" property="updateUid" /> <id column="login_ip" property="loginIp" /> <id column="login_addr" property="loginAddr" /> </resultMap> <sql id="Base_Column_List"> id, login_name, password, nickname, type, state, note, create_time, update_time, update_uid, login_ip, login_addr </sql> </mapper>
import com.xin.usercenter.entity.User; import com.baomidou.mybatisplus.extension.service.IService; /** * Copyright: Copyright (c) 2019 * * <p>說明: 用戶服務層</P> * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *------------------------------------------------------------* * 2019年4月9日 BianPeng V1.0 initialize */ public interface UserService extends IService<User> { }
import com.xin.usercenter.entity.User; import com.xin.usercenter.dao.UserDao; import com.xin.usercenter.service.UserService; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; /** * Copyright: Copyright (c) 2019 * * <p>說明: 用戶服務實現層</P> * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *------------------------------------------------------------* * 2019年4月9日 BianPeng V1.0 initialize */ @Service public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { }
import com.item.util.JsonResult; import com.xin.usercenter.entity.User; import com.xin.usercenter.service.UserService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * Copyright: Copyright (c) 2019 * * <p>說明: 用戶API接口層</P> * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------------* * 2019年4月9日 BianPeng V1.0 initialize */ @Api(description = "用戶",value="用戶" ) @RestController @RequestMapping("/user") public class UserController { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired public UserService userServiceImpl; /** * @explain 查詢用戶對象 <swagger GET請求> * @param 對象參數:id * @return user * @author BianPeng * @time 2019年4月9日 */ @GetMapping("/getUserById/{id}") @ApiOperation(value = "獲取用戶信息", notes = "獲取用戶信息[user],做者:BianPeng") @ApiImplicitParam(paramType="path", name = "id", value = "用戶id", required = true, dataType = "Long") public JsonResult<User> getUserById(@PathVariable("id")Long id){ JsonResult<User> result=new JsonResult<User>(); try { User user=userServiceImpl.getById(id); if (user!=null) { result.setType("success"); result.setMessage("成功"); result.setData(user); } else { logger.error("獲取用戶失敗ID:"+id); result.setType("fail"); result.setMessage("你獲取的用戶不存在"); } } catch (Exception e) { logger.error("獲取用戶執行異常:"+e.getMessage()); result=new JsonResult<User>(e); } return result; } /** * @explain 添加或者更新用戶對象 * @param 對象參數:user * @return int * @author BianPeng * @time 2019年4月9日 */ @PostMapping("/insertSelective") @ApiOperation(value = "添加用戶", notes = "添加用戶[user],做者:BianPeng") public JsonResult<User> insertSelective(User user){ JsonResult<User> result=new JsonResult<User>(); try { boolean rg=userServiceImpl.saveOrUpdate(user); if (rg) { result.setType("success"); result.setMessage("成功"); result.setData(user); } else { logger.error("添加用戶執行失敗:"+user.toString()); result.setType("fail"); result.setMessage("執行失敗,請稍後重試"); } } catch (Exception e) { logger.error("添加用戶執行異常:"+e.getMessage()); result=new JsonResult<User>(e); } return result; } /** * @explain 刪除用戶對象 * @param 對象參數:id * @return int * @author BianPeng * @time 2019年4月9日 */ @PostMapping("/deleteByPrimaryKey") @ApiOperation(value = "刪除用戶", notes = "刪除用戶,做者:BianPeng") @ApiImplicitParam(paramType="query", name = "id", value = "用戶id", required = true, dataType = "Long") public JsonResult<Object> deleteByPrimaryKey(Long id){ JsonResult<Object> result=new JsonResult<Object>(); try { boolean reg=userServiceImpl.removeById(id); if (reg) { result.setType("success"); result.setMessage("成功"); result.setData(id); } else { logger.error("刪除用戶失敗ID:"+id); result.setType("fail"); result.setMessage("執行錯誤,請稍後重試"); } } catch (Exception e) { logger.error("刪除用戶執行異常:"+e.getMessage()); result=new JsonResult<Object>(e); } return result; } /** * @explain 分頁條件查詢用戶 * @param 對象參數:AppPage<User> * @return PageInfo<User> * @author BianPeng * @time 2019年4月9日 */ @GetMapping("/getUserPages") @ApiOperation(value = "分頁查詢", notes = "分頁查詢返回對象[IPage<User>],做者:邊鵬") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name = "pageNum", value = "當前頁", required = true, dataType = "int"), @ApiImplicitParam(paramType="query", name = "pageSize", value = "頁行數", required = true, dataType = "int") }) public JsonResult<Object> getUserPages(Integer pageNum,Integer pageSize){ JsonResult<Object> result=new JsonResult<Object>(); Page<User> page=new Page<User>(pageNum,pageSize); QueryWrapper<User> queryWrapper =new QueryWrapper<User>(); //分頁數據 try { //List<User> list=userServiceImpl.list(queryWrapper); IPage<User> pageInfo=userServiceImpl.page(page, queryWrapper); result.setType("success"); result.setMessage("成功"); result.setData(pageInfo); } catch (Exception e) { logger.error("分頁查詢用戶執行異常:"+e.getMessage()); result=new JsonResult<Object>(e); } return result; } }
生成完畢,控制器中的JsonResult數據庫
import java.io.Serializable; import java.net.ConnectException; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright: Copyright (c) 2019 * * <p>說明: 用戶服務層</P> * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2019/4/9 flying-cattle V1.0 initialize */ public class JsonResult<T> implements Serializable{ Logger logger = LoggerFactory.getLogger(this.getClass()); private static final long serialVersionUID = 1071681926787951549L; /** * <p>返回狀態</p> */ private Boolean isTrue=true; /** *<p> 狀態碼</p> */ private String code; /** * <p>業務碼</p> */ private String type; /** *<p> 狀態說明</p> */ private String message; /** * <p>返回數據</p> */ private T data; public Boolean getTrue() { return isTrue; } public void setTrue(Boolean aTrue) { isTrue = aTrue; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getType() { return type; } public void setType(String type) { this.type = type; } /** * <p>返回成功</p> * @param type 業務碼 * @param message 錯誤說明 * @param data 數據 */ public JsonResult(String type, String message, T data) { this.isTrue=true; this.code ="0000"; this.type=type; this.message = message; this.data=data; } public JsonResult() { this.isTrue=true; this.code ="0000"; } public JsonResult(Throwable throwable) { logger.error(throwable+"tt"); this.isTrue=false; if(throwable instanceof NullPointerException){ this.code= "1001"; this.message="空指針:"+throwable; }else if(throwable instanceof ClassCastException ){ this.code= "1002"; this.message="類型強制轉換異常:"+throwable; }else if(throwable instanceof ConnectException){ this.code= "1003"; this.message="連接失敗:"+throwable; }else if(throwable instanceof IllegalArgumentException ){ this.code= "1004"; this.message="傳遞非法參數異常:"+throwable; }else if(throwable instanceof NumberFormatException){ this.code= "1005"; this.message="數字格式異常:"+throwable; }else if(throwable instanceof IndexOutOfBoundsException){ this.code= "1006"; this.message="下標越界異常:"+throwable; }else if(throwable instanceof SecurityException){ this.code= "1007"; this.message="安全異常:"+throwable; }else if(throwable instanceof SQLException){ this.code= "1008"; this.message="數據庫異常:"+throwable; }else if(throwable instanceof ArithmeticException){ this.code= "1009"; this.message="算術運算異常:"+throwable; }else if(throwable instanceof RuntimeException){ this.code= "1010"; this.message="運行時異常:"+throwable; }else if(throwable instanceof Exception){ logger.error("未知異常:"+throwable); this.code= "9999"; this.message="未知異常"+throwable; } } }
若是你生成的分頁的方法不能分頁:根據官方提高,記得在啓動類中加入apache
@Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }