mybatis-dsc-generator
Perfect integration of lombok, swagger code generation tools, so that you no longer worry about cumbersome comments and simple interface implementation: entity integration, format verification, swagger; dao auto add @ mapper, service auto comment and dependency; controller to achieve single table add / modify, and realize swaggers api documents.
Source address
- GitHub:https://github.com/flying-cattle/mybatis-dsc-generator
- Code cloud: https://gitee.com/flying-cattle/mybatis-dsc-generator
MAVEN address
Version 2.1.0 is not integrated with mybatis plus - source branch master
<dependency> <groupId>com.github.flying-cattle</groupId> <artifactId>mybatis-dsc-generator</artifactId> <version>2.1.0.RELEASE</version> </dependency>
Version 3.0.0 is an integrated version of mybatis plus - the source branch of mybatisPlus
<dependency> <groupId>com.github.flying-cattle</groupId> <artifactId>mybatis-dsc-generator</artifactId> <version>2.1.0.RELEASE</version> </dependency>
Data table structure style
CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID', `login_name` varchar(40) DEFAULT NULL COMMENT 'Login name', `password` varchar(100) NOT NULL COMMENT 'Secret', `nickname` varchar(50) NOT NULL COMMENT 'Nickname?', `type` int(10) unsigned DEFAULT NULL COMMENT 'type', `state` int(10) unsigned NOT NULL DEFAULT '1' COMMENT 'Status:-1 Failed, 0 waiting,1 Success', `note` varchar(255) DEFAULT NULL COMMENT 'Remarks', `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time', `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time', `update_uid` bigint(20) DEFAULT '0' COMMENT 'Modified by user ID', `login_ip` varchar(50) DEFAULT NULL COMMENT 'Sign in IP address', `login_addr` varchar(100) DEFAULT NULL COMMENT 'Login address', PRIMARY KEY (`id`), UNIQUE KEY `login_name` (`login_name`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
It is required that there must be table annotation, primary key as id, and all fields must be annotated (easy to generate java annotation swagger, etc.).
Generated entity class
The generation method refers to the following in the source code: https://github.com/flying-cattle/mybatis-dsc-generator/blob/mybatisPlus/src/main/java/com/github/mybatis/fl/test/TestMain.java
results of enforcement
Entity class
/** * @filename:Order 2018 July 5th 2013 * @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>Note: user entity class < / P > * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------------* * 2019 April 9, 2010 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 = "user ID") private Long id; @ApiModelProperty(name = "loginName" , value = "Login account") private String loginName; @ApiModelProperty(name = "password" , value = "Login password") private String password; @ApiModelProperty(name = "nickname" , value = "User nickname") private String nickname; @ApiModelProperty(name = "type" , value = "customer type") private Integer type; @ApiModelProperty(name = "state" , value = "User status") private Integer state; @ApiModelProperty(name = "note" , value = "Remarks") 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 = "User creation time") 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 = "Modification time") private Date updateTime; @ApiModelProperty(name = "updateUid" , value = "Modified by user ID") private Long updateUid; @ApiModelProperty(name = "loginIp" , value = "Sign in IP") private String loginIp; @ApiModelProperty(name = "loginIp" , value = "Login address") private String loginAddr; @Override protected Serializable pkVal() { return this.id; } }
DAO
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.xin.usercenter.entity.User; /** * Copyright: Copyright (c) 2019 * * <p>Note: user data access layer < / P > * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------------* * 2019 April 9, 2010 bianpeng v1.0 initialize */ @Mapper public interface UserDao extends BaseMapper<User> { }
Generated XML
<?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>
Generated SERVICE
import com.xin.usercenter.entity.User; import com.baomidou.mybatisplus.extension.service.IService; /** * Copyright: Copyright (c) 2019 * * <p>Note: user service layer < / P > * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *------------------------------------------------------------* * 2019 April 9, 2010 bianpeng v1.0 initialize */ public interface UserService extends IService<User> { }
Generated service? Impl
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>Note: user service implementation layer < / P > * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *------------------------------------------------------------* * 2019 April 9, 2010 bianpeng v1.0 initialize */ @Service public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { }
Generated CONTROLLER
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>Note: user API interface layer < / P > * @version: V1.0 * @author: BianPeng * * Modification History: * Date Author Version Description *---------------------------------------------------------------* * 2019 April 9, 2010 bianpeng v1.0 initialize */ @Api(description = "user",value="user" ) @RestController @RequestMapping("/user") public class UserController { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired public UserService userServiceImpl; /** * @explain Query user object < swagger get request > * @param Object parameter: id * @return user * @author BianPeng * @time 2019 April 9th 2013 */ @GetMapping("/getUserById/{id}") @ApiOperation(value = "Get user information", notes = "Get user information[user],Author: BianPeng") @ApiImplicitParam(paramType="path", name = "id", value = "user 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("Success"); result.setData(user); } else { logger.error("Failed to get user ID: "+id); result.setType("fail"); result.setMessage("The user you obtained does not exist"); } } catch (Exception e) { logger.error("Get user execution exception:"+e.getMessage()); result=new JsonResult<User>(e); } return result; } /** * @explain Add or update user objects * @param Object parameters: user * @return int * @author BianPeng * @time 2019 April 9th 2013 */ @PostMapping("/insertSelective") @ApiOperation(value = "Add user", notes = "Add user[user],Author: 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("Success"); result.setData(user); } else { logger.error("Add user execution failed:"+user.toString()); result.setType("fail"); result.setMessage("Execution failed, please try again later"); } } catch (Exception e) { logger.error("Add user execution exception:"+e.getMessage()); result=new JsonResult<User>(e); } return result; } /** * @explain Delete user object * @param Object parameter: id * @return int * @author BianPeng * @time 2019 April 9th 2013 */ @PostMapping("/deleteByPrimaryKey") @ApiOperation(value = "delete user", notes = "delete user,Author: BianPeng") @ApiImplicitParam(paramType="query", name = "id", value = "user 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("Success"); result.setData(id); } else { logger.error("Failed to delete user ID: "+id); result.setType("fail"); result.setMessage("Execution error, please try again later"); } } catch (Exception e) { logger.error("Delete user execution exception:"+e.getMessage()); result=new JsonResult<Object>(e); } return result; } /** * @explain Paging condition query user * @param Object parameter: apppage < user > * @return PageInfo<User> * @author BianPeng * @time 2019 April 9th 2013 */ @GetMapping("/getUserPages") @ApiOperation(value = "Paging query", notes = "Paging query return object[IPage<User>],Author: Bian Peng") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name = "pageNum", value = "Current page", required = true, dataType = "int"), @ApiImplicitParam(paramType="query", name = "pageSize", value = "Page row number", 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>(); //Paging data try { //List<User> list=userServiceImpl.list(queryWrapper); IPage<User> pageInfo=userServiceImpl.page(page, queryWrapper); result.setType("success"); result.setMessage("Success"); result.setData(pageInfo); } catch (Exception e) { logger.error("Paging query user execution exception:"+e.getMessage()); result=new JsonResult<Object>(e); } return result; } }
After generation, JsonResult in the controller
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>Note: user service layer < / 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>Return to status</p> */ private Boolean isTrue=true; /** *<p> Status code</p> */ private String code; /** * <p>Business code</p> */ private String type; /** *<p> Status description</p> */ private String message; /** * <p>Return data</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>Return success</p> * @param type Business code * @param message Error description * @param data 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="Null pointer:"+throwable; }else if(throwable instanceof ClassCastException ){ this.code= "1002"; this.message="Type cast exception:"+throwable; }else if(throwable instanceof ConnectException){ this.code= "1003"; this.message="Link failed:"+throwable; }else if(throwable instanceof IllegalArgumentException ){ this.code= "1004"; this.message="Pass illegal parameter exception:"+throwable; }else if(throwable instanceof NumberFormatException){ this.code= "1005"; this.message="Number format exception:"+throwable; }else if(throwable instanceof IndexOutOfBoundsException){ this.code= "1006"; this.message="Subscript out of range exception:"+throwable; }else if(throwable instanceof SecurityException){ this.code= "1007"; this.message="Security exception:"+throwable; }else if(throwable instanceof SQLException){ this.code= "1008"; this.message="Database exception:"+throwable; }else if(throwable instanceof ArithmeticException){ this.code= "1009"; this.message="Arithmetic operation exception:"+throwable; }else if(throwable instanceof RuntimeException){ this.code= "1010"; this.message="Runtime exception:"+throwable; }else if(throwable instanceof Exception){ logger.error("Unknown exception:"+throwable); this.code= "9999"; this.message="Unknown anomaly"+throwable; } } }
If the paging method you generate cannot be paged: according to the official promotion, remember to add
@Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }