mysql8+mybatis

mybatis-dsc-generator

Fork me on Gitee

还在为写swagger而烦恼吗?还在为忘记写注释而烦恼吗?还在为写简单的api接口而烦恼吗?mybatis-dsc-generator完美集成lombok,swagger的代码生成工具,让你不再为繁琐的注释和简单的接口实现而烦恼:entity集成,格式校验,swagger; dao自动加@ mapper,service自动注释和依赖; 控制器实现单表的增副改查,并实现swaggers的api文档。

源码地址

MAVEN地址

2.1.0版本是未集成Mybatis-plus版本——源码分支master

1<dependency> 2 <groupId>com.github.flying-cattle</groupId> 3 <artifactId>mybatis-dsc-generator</artifactId> 4 <version>2.1.0.RELEASE</version> 5</dependency>

3.0.0版本是集成了Mybatis-plus版本——源码分支mybatisPlus

1<dependency> 2 <groupId>com.github.flying-cattle</groupId> 3 <artifactId>mybatis-dsc-generator</artifactId> 4 <version>3.0.0.RELEASE</version> 5</dependency>

数据表结构样式

1CREATE TABLE `user` ( 2 `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID', 3 `login_name` varchar(40) DEFAULT NULL COMMENT '登录名', 4 `password` varchar(100) NOT NULL COMMENT '秘密', 5 `nickname` varchar(50) NOT NULL COMMENT '昵称', 6 `type` int(10) unsigned DEFAULT NULL COMMENT '类型', 7 `state` int(10) unsigned NOT NULL DEFAULT '1' COMMENT '状态:-1失败,0等待,1成功', 8 `note` varchar(255) DEFAULT NULL COMMENT '备注', 9 `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', 10 `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', 11 `update_uid` bigint(20) DEFAULT '0' COMMENT '修改人用户ID', 12 `login_ip` varchar(50) DEFAULT NULL COMMENT '登录IP地址', 13 `login_addr` varchar(100) DEFAULT NULL COMMENT '登录地址', 14 PRIMARY KEY (`id`), 15 UNIQUE KEY `login_name` (`login_name`) 16) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

要求必须有表注释,要求必须有主键为id,所有字段必须有注释(便于生成java注释swagger等)。

生成的实体类

生成方法参考源码中的:https://gitee.com/flying-cattle/mybatis-dsc-generator/blob/master/src/main/java/com/github/mybatis/fl/test/TestMain.java

执行结果

实体类

1/** 2 * @filename:Order 2018年7月5日 3 * @project deal-center V1.0 4 * Copyright(c) 2018 BianP Co. Ltd. 5 * All right reserved. 6 */ 7import com.baomidou.mybatisplus.annotation.IdType; 8import com.baomidou.mybatisplus.annotation.TableId; 9import com.baomidou.mybatisplus.extension.activerecord.Model; 10import com.fasterxml.jackson.annotation.JsonFormat; 11import io.swagger.annotations.ApiModelProperty; 12import lombok.Data; 13import lombok.EqualsAndHashCode; 14import lombok.experimental.Accessors; 15import java.util.Date; 16import org.springframework.format.annotation.DateTimeFormat; 17import java.io.Serializable; 18 19/** 20 * Copyright: Copyright (c) 2019 21 * 22 * <p>说明: 用户实体类</P> 23 * @version: V1.0 24 * @author: BianPeng 25 * 26 * Modification History: 27 * Date Author Version Description 28 *---------------------------------------------------------------* 29 * 2019年4月9日 BianPeng V1.0 initialize 30 */ 31@Data 32@EqualsAndHashCode(callSuper = false) 33@Accessors(chain = true) 34@Data 35@EqualsAndHashCode(callSuper = false) 36@Accessors(chain = true) 37public class User extends Model<User> { 38 39 private static final long serialVersionUID = 1L; 40 @TableId(value = "id", type = IdType.AUTO) 41 @ApiModelProperty(name = "id" , value = "用户ID") 42 private Long id; 43 44 @ApiModelProperty(name = "loginName" , value = "登录账户") 45 private String loginName; 46 47 @ApiModelProperty(name = "password" , value = "登录密码") 48 private String password; 49 50 @ApiModelProperty(name = "nickname" , value = "用户昵称") 51 private String nickname; 52 53 @ApiModelProperty(name = "type" , value = "用户类型") 54 private Integer type; 55 56 @ApiModelProperty(name = "state" , value = "用户状态") 57 private Integer state; 58 59 @ApiModelProperty(name = "note" , value = "备注") 60 private String note; 61 62 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 63 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 64 @ApiModelProperty(name = "createTime" , value = "用户创建时间") 65 private Date createTime; 66 67 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 68 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 69 @ApiModelProperty(name = "updateTime" , value = "修改时间") 70 private Date updateTime; 71 72 @ApiModelProperty(name = "updateUid" , value = "修改人用户ID") 73 private Long updateUid; 74 75 @ApiModelProperty(name = "loginIp" , value = "登录IP") 76 private String loginIp; 77 78 @ApiModelProperty(name = "loginIp" , value = "登录地址") 79 private String loginAddr; 80 81 @Override 82 protected Serializable pkVal() { 83 return this.id; 84 } 85}

DAO

1import com.baomidou.mybatisplus.core.mapper.BaseMapper; 2import org.apache.ibatis.annotations.Mapper; 3import com.xin.usercenter.entity.User; 4 5/** 6 * Copyright: Copyright (c) 2019 7 * 8 * <p>说明: 用户数据访问层</P> 9 * @version: V1.0 10 * @author: BianPeng 11 * 12 * Modification History: 13 * Date Author Version Description 14 *---------------------------------------------------------------* 15 * 2019年4月9日 BianPeng V1.0 initialize 16 */ 17@Mapper 18public interface UserDao extends BaseMapper<User> { 19 20}

生成的XML

1<?xml version="1.0" encoding="UTF-8"?> 2<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3<mapper namespace="com.xin.usercenter.dao.UserDao"> 4 5 <resultMap id="BaseResultMap" type="com.xin.usercenter.entity.User"> 6 <id column="id" property="id" /> 7 <id column="login_name" property="loginName" /> 8 <id column="password" property="password" /> 9 <id column="nickname" property="nickname" /> 10 <id column="type" property="type" /> 11 <id column="state" property="state" /> 12 <id column="note" property="note" /> 13 <id column="create_time" property="createTime" /> 14 <id column="update_time" property="updateTime" /> 15 <id column="update_uid" property="updateUid" /> 16 <id column="login_ip" property="loginIp" /> 17 <id column="login_addr" property="loginAddr" /> 18 </resultMap> 19 <sql id="Base_Column_List"> 20 id, login_name, password, nickname, type, state, note, create_time, update_time, update_uid, login_ip, login_addr 21 </sql> 22</mapper>

生成的SERVICE

1import com.xin.usercenter.entity.User; 2import com.baomidou.mybatisplus.extension.service.IService; 3/** 4 * Copyright: Copyright (c) 2019 5 * 6 * <p>说明: 用户服务层</P> 7 * @version: V1.0 8 * @author: BianPeng 9 * 10 * Modification History: 11 * Date Author Version Description 12 *------------------------------------------------------------* 13 * 2019年4月9日 BianPeng V1.0 initialize 14 */ 15public interface UserService extends IService<User> { 16 17}

生成的SERVICE_IMPL

1import com.xin.usercenter.entity.User; 2import com.xin.usercenter.dao.UserDao; 3import com.xin.usercenter.service.UserService; 4import org.springframework.stereotype.Service; 5import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 6 7/** 8 * Copyright: Copyright (c) 2019 9 * 10 * <p>说明: 用户服务实现层</P> 11 * @version: V1.0 12 * @author: BianPeng 13 * 14 * Modification History: 15 * Date Author Version Description 16 *------------------------------------------------------------* 17 * 2019年4月9日 BianPeng V1.0 initialize 18 */ 19@Service 20public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { 21 22}

生成的CONTROLLER

1import com.item.util.JsonResult; 2import com.xin.usercenter.entity.User; 3import com.xin.usercenter.service.UserService; 4import org.springframework.web.bind.annotation.GetMapping; 5import org.springframework.web.bind.annotation.PathVariable; 6import org.springframework.web.bind.annotation.PostMapping; 7import org.springframework.web.bind.annotation.RequestMapping; 8import org.springframework.web.bind.annotation.RestController; 9import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; 10import com.baomidou.mybatisplus.core.metadata.IPage; 11import com.baomidou.mybatisplus.extension.plugins.pagination.Page; 12import io.swagger.annotations.Api; 13import io.swagger.annotations.ApiImplicitParam; 14import io.swagger.annotations.ApiImplicitParams; 15import io.swagger.annotations.ApiOperation; 16import org.slf4j.Logger; 17import org.slf4j.LoggerFactory; 18import org.springframework.beans.factory.annotation.Autowired; 19 20/** 21 * Copyright: Copyright (c) 2019 22 * 23 * <p>说明: 用户API接口层</P> 24 * @version: V1.0 25 * @author: BianPeng 26 * 27 * Modification History: 28 * Date Author Version Description 29 *---------------------------------------------------------------* 30 * 2019年4月9日 BianPeng V1.0 initialize 31 */ 32@Api(description = "用户",value="用户" ) 33@RestController 34@RequestMapping("/user") 35public class UserController { 36 37 Logger logger = LoggerFactory.getLogger(this.getClass()); 38 39 @Autowired 40 public UserService userServiceImpl; 41 42 /** 43 * @explain 查询用户对象 <swagger GET请求> 44 * @param 对象参数:id 45 * @return user 46 * @author BianPeng 47 * @time 2019年4月9日 48 */ 49 @GetMapping("/getUserById/{id}") 50 @ApiOperation(value = "获取用户信息", notes = "获取用户信息[user],作者:BianPeng") 51 @ApiImplicitParam(paramType="path", name = "id", value = "用户id", required = true, dataType = "Long") 52 public JsonResult<User> getUserById(@PathVariable("id")Long id){ 53 JsonResult<User> result=new JsonResult<User>(); 54 try { 55 User user=userServiceImpl.getById(id); 56 if (user!=null) { 57 result.setType("success"); 58 result.setMessage("成功"); 59 result.setData(user); 60 } else { 61 logger.error("获取用户失败ID:"+id); 62 result.setType("fail"); 63 result.setMessage("你获取的用户不存在"); 64 } 65 } catch (Exception e) { 66 logger.error("获取用户执行异常:"+e.getMessage()); 67 result=new JsonResult<User>(e); 68 } 69 return result; 70 } 71 /** 72 * @explain 添加或者更新用户对象 73 * @param 对象参数:user 74 * @return int 75 * @author BianPeng 76 * @time 2019年4月9日 77 */ 78 @PostMapping("/insertSelective") 79 @ApiOperation(value = "添加用户", notes = "添加用户[user],作者:BianPeng") 80 public JsonResult<User> insertSelective(User user){ 81 JsonResult<User> result=new JsonResult<User>(); 82 try { 83 boolean rg=userServiceImpl.saveOrUpdate(user); 84 if (rg) { 85 result.setType("success"); 86 result.setMessage("成功"); 87 result.setData(user); 88 } else { 89 logger.error("添加用户执行失败:"+user.toString()); 90 result.setType("fail"); 91 result.setMessage("执行失败,请稍后重试"); 92 } 93 } catch (Exception e) { 94 logger.error("添加用户执行异常:"+e.getMessage()); 95 result=new JsonResult<User>(e); 96 } 97 return result; 98 } 99 100 /** 101 * @explain 删除用户对象 102 * @param 对象参数:id 103 * @return int 104 * @author BianPeng 105 * @time 2019年4月9日 106 */ 107 @PostMapping("/deleteByPrimaryKey") 108 @ApiOperation(value = "删除用户", notes = "删除用户,作者:BianPeng") 109 @ApiImplicitParam(paramType="query", name = "id", value = "用户id", required = true, dataType = "Long") 110 public JsonResult<Object> deleteByPrimaryKey(Long id){ 111 JsonResult<Object> result=new JsonResult<Object>(); 112 try { 113 boolean reg=userServiceImpl.removeById(id); 114 if (reg) { 115 result.setType("success"); 116 result.setMessage("成功"); 117 result.setData(id); 118 } else { 119 logger.error("删除用户失败ID:"+id); 120 result.setType("fail"); 121 result.setMessage("执行错误,请稍后重试"); 122 } 123 } catch (Exception e) { 124 logger.error("删除用户执行异常:"+e.getMessage()); 125 result=new JsonResult<Object>(e); 126 } 127 return result; 128 } 129 130 /** 131 * @explain 分页条件查询用户 132 * @param 对象参数:AppPage<User> 133 * @return PageInfo<User> 134 * @author BianPeng 135 * @time 2019年4月9日 136 */ 137 @GetMapping("/getUserPages") 138 @ApiOperation(value = "分页查询", notes = "分页查询返回对象[IPage<User>],作者:边鹏") 139 @ApiImplicitParams({ 140 @ApiImplicitParam(paramType="query", name = "pageNum", value = "当前页", required = true, dataType = "int"), 141 @ApiImplicitParam(paramType="query", name = "pageSize", value = "页行数", required = true, dataType = "int") 142 }) 143 public JsonResult<Object> getUserPages(Integer pageNum,Integer pageSize){ 144 145 JsonResult<Object> result=new JsonResult<Object>(); 146 Page<User> page=new Page<User>(pageNum,pageSize); 147 QueryWrapper<User> queryWrapper =new QueryWrapper<User>(); 148 //分页数据 149 try { 150 //List<User> list=userServiceImpl.list(queryWrapper); 151 IPage<User> pageInfo=userServiceImpl.page(page, queryWrapper); 152 result.setType("success"); 153 result.setMessage("成功"); 154 result.setData(pageInfo); 155 } catch (Exception e) { 156 logger.error("分页查询用户执行异常:"+e.getMessage()); 157 result=new JsonResult<Object>(e); 158 } 159 return result; 160 } 161}

生成完毕,控制器中的JsonResult

1import java.io.Serializable; 2import java.net.ConnectException; 3import java.sql.SQLException; 4import org.slf4j.Logger; 5import org.slf4j.LoggerFactory; 6/** 7 * Copyright: Copyright (c) 2019 8 * 9 * <p>说明: 用户服务层</P> 10 * @version: V1.0 11 * @author: BianPeng 12 * 13 * Modification History: 14 * Date Author Version Description 15 *---------------------------------------------------------* 16 * 2019/4/9 flying-cattle V1.0 initialize 17 */ 18public class JsonResult<T> implements Serializable{ 19 20 Logger logger = LoggerFactory.getLogger(this.getClass()); 21 private static final long serialVersionUID = 1071681926787951549L; 22 23 /** 24 * <p>返回状态</p> 25 */ 26 private Boolean isTrue=true; 27 /** 28 *<p> 状态码</p> 29 */ 30 private String code; 31 /** 32 * <p>业务码</p> 33 */ 34 private String type; 35 /** 36 *<p> 状态说明</p> 37 */ 38 private String message; 39 /** 40 * <p>返回数据</p> 41 */ 42 private T data; 43 public Boolean getTrue() { 44 return isTrue; 45 } 46 public void setTrue(Boolean aTrue) { 47 isTrue = aTrue; 48 } 49 public String getCode() { 50 return code; 51 } 52 public void setCode(String code) { 53 this.code = code; 54 } 55 public String getMessage() { 56 return message; 57 } 58 public void setMessage(String message) { 59 this.message = message; 60 } 61 public T getData() { 62 return data; 63 } 64 public void setData(T data) { 65 this.data = data; 66 } 67 public String getType() { 68 return type; 69 } 70 public void setType(String type) { 71 this.type = type; 72 } 73 /** 74 * <p>返回成功</p> 75 * @param type 业务码 76 * @param message 错误说明 77 * @param data 数据 78 */ 79 public JsonResult(String type, String message, T data) { 80 this.isTrue=true; 81 this.code ="0000"; 82 this.type=type; 83 this.message = message; 84 this.data=data; 85 } 86 public JsonResult() { 87 this.isTrue=true; 88 this.code ="0000"; 89 } 90 public JsonResult(Throwable throwable) { 91 logger.error(throwable+"tt"); 92 this.isTrue=false; 93 if(throwable instanceof NullPointerException){ 94 this.code= "1001"; 95 this.message="空指针:"+throwable; 96 }else if(throwable instanceof ClassCastException ){ 97 this.code= "1002"; 98 this.message="类型强制转换异常:"+throwable; 99 }else if(throwable instanceof ConnectException){ 100 this.code= "1003"; 101 this.message="链接失败:"+throwable; 102 }else if(throwable instanceof IllegalArgumentException ){ 103 this.code= "1004"; 104 this.message="传递非法参数异常:"+throwable; 105 }else if(throwable instanceof NumberFormatException){ 106 this.code= "1005"; 107 this.message="数字格式异常:"+throwable; 108 }else if(throwable instanceof IndexOutOfBoundsException){ 109 this.code= "1006"; 110 this.message="下标越界异常:"+throwable; 111 }else if(throwable instanceof SecurityException){ 112 this.code= "1007"; 113 this.message="安全异常:"+throwable; 114 }else if(throwable instanceof SQLException){ 115 this.code= "1008"; 116 this.message="数据库异常:"+throwable; 117 }else if(throwable instanceof ArithmeticException){ 118 this.code= "1009"; 119 this.message="算术运算异常:"+throwable; 120 }else if(throwable instanceof RuntimeException){ 121 this.code= "1010"; 122 this.message="运行时异常:"+throwable; 123 }else if(throwable instanceof Exception){ 124 logger.error("未知异常:"+throwable); 125 this.code= "9999"; 126 this.message="未知异常"+throwable; 127 } 128 } 129}

如果你生成的分页的方法不能分页:根据官方提升,记得在启动类中加入

1@Bean 2public PaginationInterceptor paginationInterceptor() { 3 return new PaginationInterceptor(); 4}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

mysql8+mybatis - HelloWorld