mybatis-plus3.5.3.1、freemarker

mybatis-plus3.5.3.1、freemarker

  1. 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>
  1. 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;

/**
 * @web1: https://juejin.cn/post/7033399493684903949
 * @web2: https://blog.csdn.net/weixin_40156790/article/details/113754543?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-113754543-blog-131182561.235^v38^pc_relevant_anti_vip_base&spm=1001.2101.3001.4242.1&utm_relevant_index=3
 */
@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";

	/**
	 * 方式1
	 * 
	 * @param tableName 表名
	 */
	public static void Generation1(String... tableName) {
		// 1、配置数据源
		FastAutoGenerator.create(url, username, password)
				// 2、全局配置
				.globalConfig(builder -> {
					builder.author("Johnny")// 作者名
							.enableSwagger()// 启用swagger
							.dateType(DateType.ONLY_DATE) // 设置事件策略
							.disableOpenDir()// 禁止打开目录,默认false
							.commentDate("yyyy-MM-dd")// 注释日期 默认值: yyyy-MM-dd
							.outputDir(System.getProperty("user.dir") + "/src/main/java");// 指定输出目录
//							.enableKotlin()//开启 kotlin 模式 默认值:false
					// 3、包配置
				}).packageConfig(builder -> {
					builder.parent("cn.frameworkModule.V2")// 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
							.moduleName("")// 父包模块名 默认值:无
							.controller("controller") // Controller 包名
							.service("service") // Service 包名
							.serviceImpl("service.impl") // ***ServiceImpl 包名
							.mapper("mapper") // Mapper 包名
							.xml("mapperxml") // Mapper XML 包名
							.entity("model") // entity 实体类包名
							// 自定义mapper.xml文件输出目录
							.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapperxml"));
					// 4、策略配置
				}).strategyConfig(builder -> {
					builder.addInclude(tableName)// 设置要生成的表名
							.addFieldPrefix("")// 指定表的哪些字段去掉

							.serviceBuilder()// 服务层
							.formatServiceFileName("%sService")// 这里整体为 %s(代表表名)+ 后面的Service
							.formatServiceImplFileName("%sServiceImpl")//
							.enableFileOverride()// 覆盖已有文件Service/ServiceImpl

							.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()// 覆盖已有文件entity
//							.enableColumnConstant()// 生成字段常量
//							.enableLombok()// 支持lombok

							.controllerBuilder()// 控制器层
							.formatFileName("%sController")// 格式化文件名称
							.enableRestStyle()// 生成@restcontroller 风格
							.enableFileOverride()// 覆盖已有文件Controller

							.mapperBuilder()// 数据源
							.superClass(BaseMapper.class)// 继承
							.formatMapperFileName("%sDao")// 格式化文件名称
							.mapperAnnotation(Mapper.class)//
							.formatXmlFileName("%sMapper")// 格式化文件名称
							.enableFileOverride();// 覆盖已有文件Dao/Mapper
//					 5、自定义注入配置
				}).injectionConfig(consumer -> {
					Map<String, String> customFile = new HashMap<>();
//					 配置自定义模板引擎,比如freemarker
//					customFile.put("EntityExample.java", "/templates/EntityExample.java.vm");
//					consumer.customFile(customFile);
//					 6、模板
				}).templateConfig(builder -> {
//					FreeMarker简介:http://www.freemarker.net/#2
//					builder.controller(controller)//
//							.service(service)//
//							.serviceImpl(serviceImpl);//
//							.mapper(mapper)//
//							.xml(xml)//
//							.entity(entity)//
//							.entityKt(entityKt);//
				}).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请输入作者名称?"))// johnny
						.outputDir(System.getProperty("user.dir") + "/src/main/java")//
						.commentDate("yyyy-MM-dd hh:mm:ss")//
						.dateType(DateType.TIME_PACK)//
						.enableSwagger()//
						.disableOpenDir())//
//						.enableKotlin()//开启 kotlin 模式 默认值:false
//				 包配置
				.packageConfig((scanner, builder) -> builder.parent(scanner.apply("=================包配置=================\n请输入包名?"))// cn.frameworkModule
						.moduleName(scanner.apply("请输入父包模块名?"))// mybatisplus
						.controller("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")))// all
							.addFieldPrefix("")// 指定表的哪些字段去掉

							.serviceBuilder()//
							.formatServiceFileName("%sService")// 格式化service实现类文件名称
							.formatServiceImplFileName("%sServiceImpl")// 格式化service实现类文件名称
							.enableFileOverride()// 覆盖已有文件Service/ServiceImpl

							.entityBuilder() // 实体类策略配置
							.disableSerialVersionUID()// 禁用生成serialVersionUID
							.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()// 覆盖已有文件entity
//							.enableColumnConstant()// 生成字段常量
//							.enableLombok()// 支持lombok

							.controllerBuilder()//
							.formatFileName("%sController")// 格式化文件名称
							.enableRestStyle()// 开启生成@RestController控制器
							.enableFileOverride()// 覆盖已有文件Controller

							.mapperBuilder()//
							.superClass(BaseMapper.class)// 父类Mapper
							.formatMapperFileName("%sMapper")// 格式化Mapper文件名称
							.mapperAnnotation(Mapper.class)// @Mapper
							.formatXmlFileName("%sMapper")// 格式化Xml文件名称
							.enableFileOverride();// 覆盖已有文件
				})
				// 模板引擎配置
				.templateEngine(new VelocityTemplateEngine())// 默认模板
				// .templateEngine(new BeetlTemplateEngine())
				// .templateEngine(new FreemarkerTemplateEngine())
				.execute();
	}

	// 处理 all 情况
	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");
		// Generation2();
	}
}

  1. 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;
    }
}

  1. CommonResponse.java
package com.example.mybatisplusgen.utils.response;

/**
 * @author
 */
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);
	}

}

  1. 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='用户角色关联表';




  1. 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;

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#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>


  1. service.java.ftl
package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
/**
* <p>
    * ${table.comment!} 服务类
    * </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

        /**
        * 获取${entity}列表
        * @return
        */
        List<${entity}> select${entity}List(${entity} ${table.entityPath});

        /**
        * 插入${entity}
        * @param blogTag
        * @return
        */
        boolean insert${entity}(${entity} ${table.entityPath});

        /**
        * 修改${entity}
        * @param blogTag
        * @return
        */
        boolean update${entity}(${entity} ${table.entityPath});

        /**
        * 删除${entity}
        * @param id
        * @return
        */
        boolean delete${entity}(Long id);
}
</#if>

  1. 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;
/**
 * <p>
 * ${table.comment!} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值