mybatis-plus3.5.3.1、freemarker
- pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>com.kangyonggan</groupId>
<artifactId>freemarker</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
- CodeGeneration.java
package mybatisplus;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
@SuppressWarnings("unused")
public class CodeGeneration {
private static String url = "jdbc:mysql://localhost:8011/test";
private static String username = "xoop_root";
private static String password = "654321";
private static String entity = "/templates/entity.java";
private static String entityKt = "/templates/entityKt.java";
private static String controller = "/templates/controller.java";
private static String service = "/templates/service.java";
private static String serviceImpl = "/templates/serviceImpl.java";
private static String mapper = "/templates/mapper.java";
private static String xml = "/templates/mapper.xml";
public static void Generation1(String... tableName) {
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
builder.author("Johnny")
.enableSwagger()
.dateType(DateType.ONLY_DATE)
.disableOpenDir()
.commentDate("yyyy-MM-dd")
.outputDir(System.getProperty("user.dir") + "/src/main/java");
}).packageConfig(builder -> {
builder.parent("cn.frameworkModule.V2")
.moduleName("")
.controller("controller")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.xml("mapperxml")
.entity("model")
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapperxml"));
}).strategyConfig(builder -> {
builder.addInclude(tableName)
.addFieldPrefix("")
.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.enableFileOverride()
.entityBuilder()
.formatFileName("%sBean")
.naming(NamingStrategy.underline_to_camel)
.enableChainModel()
.addTableFills(new Property("creat_time", FieldFill.INSERT))
.addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
.logicDeletePropertyName("deleted")
.enableTableFieldAnnotation()
.enableFileOverride()
.controllerBuilder()
.formatFileName("%sController")
.enableRestStyle()
.enableFileOverride()
.mapperBuilder()
.superClass(BaseMapper.class)
.formatMapperFileName("%sDao")
.mapperAnnotation(Mapper.class)
.formatXmlFileName("%sMapper")
.enableFileOverride();
}).injectionConfig(consumer -> {
Map<String, String> customFile = new HashMap<>();
}).templateConfig(builder -> {
}).templateEngine(new FreemarkerTemplateEngine()).execute();
}
public static void Generation2() {
Scanner scan = new Scanner(System.in);
FastAutoGenerator.create(url, username, password)
.globalConfig((scanner, builder) -> builder.author(scanner.apply("=================全局配置=================\n请输入作者名称?"))
.outputDir(System.getProperty("user.dir") + "/src/main/java")
.commentDate("yyyy-MM-dd hh:mm:ss")
.dateType(DateType.TIME_PACK)
.enableSwagger()
.disableOpenDir())
.packageConfig((scanner, builder) -> builder.parent(scanner.apply("=================包配置=================\n请输入包名?"))
.moduleName(scanner.apply("请输入父包模块名?"))
.controller("controller")
.service("service")
.serviceImpl("serviceImpl")
.mapper("mapper")
.xml("mapperxml")
.entity("model")
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapperxml")))
.strategyConfig((scanner, builder) -> {
builder.addInclude(getTables(scanner.apply("=================策略配置=================\n请输入表名,多个英文逗号分隔?所有输入 all")))
.addFieldPrefix("")
.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.enableFileOverride()
.entityBuilder()
.disableSerialVersionUID()
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
.addTableFills(new Column("create_time", FieldFill.INSERT), new Column("modify_time", FieldFill.INSERT_UPDATE))
.logicDeleteColumnName("deleted")
.enableTableFieldAnnotation()
.enableFileOverride()
.controllerBuilder()
.formatFileName("%sController")
.enableRestStyle()
.enableFileOverride()
.mapperBuilder()
.superClass(BaseMapper.class)
.formatMapperFileName("%sMapper")
.mapperAnnotation(Mapper.class)
.formatXmlFileName("%sMapper")
.enableFileOverride();
})
.templateEngine(new VelocityTemplateEngine())
.execute();
}
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
public static void main(String[] args) {
Generation1("sys_log", "sys_menu", "sys_permission", "sys_role", "sys_role_permission", "sys_user", "sys_user_role");
}
}
- Code.java
package com.example.mybatisplusgen.utils.response;
public enum Code {
HTTP_SUCCESS(200,"请求成功"),
HTTP_FAIL(500, "操作失败")
;
private final Integer code;
private final String message;
Code(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
- CommonResponse.java
package com.example.mybatisplusgen.utils.response;
public class CommonResponse<T> {
private Boolean success;
private int code;
private String message;
private T data;
private Integer current;
private Integer size;
private Long total;
public Integer getCurrent() {
return current;
}
public void setCurrent(Integer current) {
this.current = current;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public CommonResponse(Boolean success, Code resultCode, T data, Integer current, Integer size, Long total) {
this.success = success;
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.data = data;
this.current = current;
this.size = size;
this.total = total;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public int getCode() {
return code;
}
public void setCode(int 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 CommonResponse() {
}
public CommonResponse(Code resultCode, Boolean success, T data) {
this.success = success;
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.data = data;
}
public CommonResponse err(int code, String message) {
this.code = code;
this.message = message;
this.success = false;
return this;
}
public static <T> CommonResponse Ipage(T data, boolean success, Integer current, Integer size, Long total) {
return new CommonResponse<>(success, Code.HTTP_SUCCESS, data, current, size, total);
}
public static <T> CommonResponse<T> ok(T data) {
return new CommonResponse<>(Code.HTTP_SUCCESS, true, data);
}
public static CommonResponse fail() {
return new CommonResponse<>(Code.HTTP_FAIL, false, null);
}
public static CommonResponse fail(int code, String message) {
return new CommonResponse<>().err(code, message);
}
}
- sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for sys_log
-- ----------------------------
DROP TABLE IF EXISTS `sys_log`;
CREATE TABLE `sys_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`log_type` varchar(50) NOT NULL COMMENT '日志类型',
`create_user_code` varchar(64) NOT NULL COMMENT '创建用户编码',
`create_user_name` varchar(100) NOT NULL COMMENT '创建用户名称',
`create_date` datetime NOT NULL COMMENT '创建时间',
`request_uri` varchar(500) DEFAULT NULL COMMENT '请求URI',
`request_method` varchar(10) DEFAULT NULL COMMENT '请求方式',
`request_params` text COMMENT '请求参数',
`request_ip` varchar(20) NOT NULL COMMENT '请求IP',
`server_address` varchar(50) NOT NULL COMMENT '请求服务器地址',
`is_exception` char(1) DEFAULT NULL COMMENT '是否异常',
`exception_info` text COMMENT '异常信息',
`start_time` datetime NOT NULL COMMENT '开始时间',
`end_time` datetime NOT NULL COMMENT '结束时间',
`execute_time` int(11) DEFAULT NULL COMMENT '执行时间',
`user_agent` varchar(500) DEFAULT NULL COMMENT '用户代理',
`device_name` varchar(100) DEFAULT NULL COMMENT '操作系统',
`browser_name` varchar(100) DEFAULT NULL COMMENT '浏览器名称',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='系统日志表';
-- ----------------------------
-- Table structure for sys_menu
-- ----------------------------
DROP TABLE IF EXISTS `sys_menu`;
CREATE TABLE `sys_menu` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`menu_name` varchar(64) DEFAULT NULL COMMENT '菜单名称',
`permission_id` varchar(64) DEFAULT NULL COMMENT '权限ID',
`url` varchar(255) DEFAULT NULL COMMENT '请求路径',
`sort` tinyint(4) DEFAULT NULL COMMENT '排序',
`style` varchar(255) DEFAULT NULL COMMENT '样式(可设置css图标)',
`parent_id` int(11) DEFAULT NULL COMMENT '父主键ID(有值的,属于该值菜单的下级菜单)',
`create_user` varchar(64) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(3) unsigned DEFAULT '0' COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='菜单表';
-- ----------------------------
-- Table structure for sys_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`permission_id` varchar(64) DEFAULT NULL COMMENT '权限ID(自定义)可设置唯一索引UNIQUE',
`permission_name` varchar(64) DEFAULT NULL COMMENT '权限名称',
`description` varchar(255) DEFAULT NULL COMMENT '描述说明',
`create_user` varchar(64) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(3) unsigned DEFAULT '0' COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='权限表';
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`role_id` varchar(64) DEFAULT NULL COMMENT '角色ID(自定义)可设置唯一索引UNIQUE',
`role_name` varchar(64) DEFAULT NULL COMMENT '角色名称',
`permission_id` varchar(64) DEFAULT NULL COMMENT '权限类别(主要定义角色属于哪种层级)',
`create_user` varchar(64) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) DEFAULT '0' COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='角色表';
-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`role_id` varchar(64) DEFAULT NULL COMMENT '角色ID',
`permission_id` varchar(64) DEFAULT NULL COMMENT '权限ID',
`create_user` varchar(64) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) DEFAULT '0' COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='角色权限关联表';
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` varchar(64) DEFAULT NULL COMMENT '用户ID(可设置唯一索引UNIQUE)',
`user_name` varchar(64) DEFAULT NULL COMMENT '用户名称',
`password` varchar(64) DEFAULT NULL COMMENT '密码',
`create_user` varchar(64) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) DEFAULT '0' COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户表';
-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` varchar(64) DEFAULT NULL COMMENT '用户ID',
`role_id` varchar(64) DEFAULT NULL COMMENT '角色ID',
`create_user` varchar(64) DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_user` varchar(64) DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`is_deleted` tinyint(1) DEFAULT '0' COMMENT '是否删除(0:正常/1:删除)',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户角色关联表';
- controller.java.ftl
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${table.entityName};
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusgen.utils.response.CommonResponse;
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
public static final Logger LOGGER = LogManager.getLogger(${table.controllerName}.class);
</#if>
@Autowired
private ${table.serviceName} ${table.entityPath}Service;
@GetMapping("/getList")
public CommonResponse getList(${entity} ${table.entityPath}) {
LOGGER.info("查找${table.comment!}:{}",${table.entityPath});
return CommonResponse.ok(${table.entityPath}Service.select${entity}List(${table.entityPath}));
}
@GetMapping("/delete")
public CommonResponse deleteByID(Long id) {
LOGGER.info("${table.comment!}删除:{}",id);
boolean b = ${table.entityPath}Service.delete${entity}(id);
if (!b) {
return CommonResponse.fail();
}
return CommonResponse.ok("删除成功");
}
@GetMapping("/insert")
public CommonResponse insert(${entity} ${table.entityPath}) {
LOGGER.info("${table.comment!}添加:{}",${table.entityPath});
boolean b = ${table.entityPath}Service.insert${entity}(${table.entityPath});
if (!b) {
return CommonResponse.fail();
}
return CommonResponse.ok("插入成功");
}
@GetMapping("/update")
public CommonResponse update(${entity} ${table.entityPath}) {
LOGGER.info("更新${table.comment!}:{}",${table.entityPath});
boolean b = ${table.entityPath}Service.update${entity}(${table.entityPath});
if (!b) {
return CommonResponse.fail();
}
return CommonResponse.ok("更新成功");
}
}
</#if>
- service.java.ftl
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
List<${entity}> select${entity}List(${entity} ${table.entityPath});
boolean insert${entity}(${entity} ${table.entityPath});
boolean update${entity}(${entity} ${table.entityPath});
boolean delete${entity}(Long id);
}
</#if>
- serviceImpl.java.ftl
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
<#if table.serviceInterface>
import ${package.Service}.${table.serviceName};
</#if>
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import java.util.List;
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>()<#if table.serviceInterface>, ${table.serviceName}</#if> {
}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}><#if table.serviceInterface> implements ${table.serviceName}</#if> {
@Override
public List<${entity}> select${entity}List(${entity} ${table.entityPath}) {
return baseMapper.selectList(null);
}
@Override
public boolean insert${entity}(${entity} ${table.entityPath}) {
return baseMapper.insert(${table.entityPath}) > 0;
}
@Override
public boolean update${entity}(${entity} ${table.entityPath}) {
return baseMapper.updateById(${table.entityPath}) > 0;
}
@Override
public boolean delete${entity}(Long id) {
return baseMapper.deleteById(id) > 0;
}
}
</#if>