• Mybatis-plus 自定义模板生成代码DTO、VO等


    Mybatis-plus 自定义模板生成代码DTO、VO等

    这里主要是介绍 Mybatis-plus 通过自定义模板自动生成增删改查等代码等,方便以后查阅!!!

    一、简介

    这里主要是介绍使用MyBatis-Plus生成基础代码,通过自定义 velocity 模板(controller、service、serviceImpl、dao)层,以及新增的DTO、queryDOT、VO类等,实现增删改查的基础代码生成。

    二、操作步骤

    (一)Maven依赖

     <dependency>
                <groupId>com.wlgroupId>
                <artifactId>cloud-coreartifactId>
            dependency>
            <dependency>
                <groupId>org.springdocgroupId>
                <artifactId>springdoc-openapi-uiartifactId>
            dependency>
    
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.25version>
            dependency>
    
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.20version>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
    
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.4.2version>
            dependency>
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-generatorartifactId>
                <version>3.4.1version>
            dependency>
    
            <dependency>
                <groupId>org.apache.velocitygroupId>
                <artifactId>velocity-engine-coreartifactId>
                <version>2.2version>
            dependency>
        dependencies>
    
        <build>
            
            <resources>
                <resource>
                    <directory>src/main/javadirectory>
                    <includes>
                        <include>**/*.xmlinclude>
                        <include>**/*.tldinclude>
                    includes>
                    
                    <filtering>falsefiltering>
                resource>
    
                <resource>
                    <directory>src/main/resourcesdirectory>
                    <includes>
                        <include>**/*.*include>
                    includes>
                    
                    <filtering>falsefiltering>
                resource>
            resources>
        build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    (二)生成代码

    package com.wl.cloud.mbg;
    
    import com.baomidou.mybatisplus.annotation.FieldFill;
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.core.toolkit.StringPool;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.InjectionConfig;
    import com.baomidou.mybatisplus.generator.config.*;
    import com.baomidou.mybatisplus.generator.config.po.TableFill;
    import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    import com.baomidou.mybatisplus.generator.config.rules.DateType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    
    import java.util.*;
    
    /**
     * @author: wanglin
     * @date: 2023-09-12 周二
     * @Version: 1.0
     * @Description:
     */
    @SuppressWarnings("all")
    public class MybatisGeneratorSystem {
    
        /**
         * 指定具体项目模块
         */
        public static String MOUDLE_NAME = "cloud-system";
        public static String AUTHOR_NAME = "wanglin";
        /**
         * 数据源信息
         */
        public static String URL = "jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
        public static String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
        public static String USERNAME = "root";
        public static String PASSWORD = "123456";
        /**
         * 包设置
         */
        public static String PARENT_PACKAGE = "com.wl.cloud.system";
        public static String MAPPER_PATH = "/src/main/resources/mapper/";
        /**
         * DTO/VO/QueryDTO 包路径
         */
        public static String PARENT_DTO_PATH = "\\src\\main\\java\\com\\wl\\cloud\\system\\support\\dto\\";
        public static String PARENT_VO_PATH = "\\src\\main\\java\\com\\wl\\cloud\\system\\support\\vo\\";
        public static String PARENT_Query_DTO_PATH = "\\src\\main\\java\\com\\wl\\cloud\\system\\support\\dto\\query\\";
        /**
         * DTO/VO/QueryDTO 包名
         */
        public static String PARENT_DTO_PACKAGE = "com.wl.cloud.system.support.dto";
        public static String PARENT_VO_PACKAGE = "com.wl.cloud.system.support.vo";
        public static String PARENT_Query_DTO_PACKAGE = "com.wl.cloud.system.support.dto.query";
        /**
         * DTO/VO/QueryDTO 自定义模板路径
         */
        public static String TEMPLATE_CONTROLLER_PATH = "/vm/java/controller.java";
        public static String TEMPLATE_SERVICE_PATH = "/vm/java/service.java";
        public static String TEMPLATE_SERVICEIMPL_PATH = "/vm/java/serviceImpl.java";
        public static String TEMPLATE_MAPPER_PATH = "/vm/java/mapper.java";
        public static String TEMPLATE_MAPPER_XML_PATH = "/vm/xml/mapper.xml.vm";
        /**
         * DTO/VO/QueryDTO 自定义模板路径
         */
        public static String TEMPLATE_DTO_PATH = "/vm/java/dto.java.vm";
        public static String TEMPLATE_VO_PATH = "/vm/java/vo.java.vm";
        public static String TEMPLATE_QUERY_DTO_PATH = "/vm/java/queryDto.java.vm";
    
        /**
         * controller 层请求路径前缀
         */
        public static String REQUEST_PATH_PREFIX = "cloud/sample/api/v1/";
    
        /**
         * 表前缀,生成实体类时,会自动去除表前缀,如:table: tb_task, class: Task
         */
        public static String TABLE_PREFIX_ENTITY = "gl_";
    
        /**
         * 需要生成的表名前缀,若为空,则默认是需要生成的表名是 TABLE_SUFFIX
         */
        public static String TABLE_PREFIX = "gl_sys_";
        /**
         * 需要生成的表名后缀,多个用逗号隔开
         */
    //    public static String TABLE_SUFFIX = "menu,role,user_role,role_menu";
        public static String TABLE_SUFFIX = "menu";
    
        /**
         * DTO 忽略的字段
         */
        public static String DTO_IGNORE_FIELD = "id,createTime,updateTime,deleted";
    
        public static void main(String[] args) {
            if ("".equals(TABLE_SUFFIX)) {
                System.out.println("----->>>需要生成的表名为空");
                return;
            }
            //表拼接
            String[] tables;
            if ("".equals(TABLE_PREFIX)) {
                tables = TABLE_SUFFIX.split(",");
            } else {
                List<String> tableList = Arrays.asList(TABLE_SUFFIX.split(","));
                tables = tableList.stream().map(MybatisGeneratorSystem::apply).toArray(String[]::new);
    
            }
            System.out.println("表:");
            Arrays.stream(tables).forEach(System.out::println);
    
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();
    
            // 全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = System.getProperty("user.dir");
            gc.setOutputDir(projectPath + "/" + MOUDLE_NAME + "/src/main/java");//设置代码生成路径
    
            gc.setFileOverride(true);//是否覆盖以前文件
            gc.setOpen(false);//是否打开生成目录
            gc.setAuthor(AUTHOR_NAME);//设置项目作者名称
            // gc.setIdType(IdType.AUTO);//设置主键策略
            gc.setIdType(IdType.ASSIGN_ID);//设置主键策略
            gc.setBaseResultMap(true);//生成基本ResultMap
            gc.setBaseColumnList(true);//生成基本ColumnList
            gc.setServiceName("%sService");//去掉服务默认前缀
            gc.setDateType(DateType.ONLY_DATE);//设置时间类型
            mpg.setGlobalConfig(gc);
    
            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl(URL);
            dsc.setDriverName(DRIVER_NAME);
            dsc.setUsername(USERNAME);
            dsc.setPassword(PASSWORD);
            mpg.setDataSource(dsc);
    
            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setParent(PARENT_PACKAGE);
            pc.setMapper("dao");
            //不生成实体类
            pc.setEntity("domain");
            pc.setService("service");
            pc.setServiceImpl("service.impl");
            pc.setController("controller");
            mpg.setPackageInfo(pc);
    
            //自定义配置,配置自定义属性注入
            InjectionConfig cfg = new InjectionConfig() {
                //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
                @Override
                public void initMap() {
                    //自定义生成模板参数
                    Map<String, Object> map = new HashMap<>();
                    map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                    //模板中获取值:${cfg.requestPathPrefix}
                    map.put("requestPathPrefix", REQUEST_PATH_PREFIX);
                    map.put("dtoPackage", PARENT_DTO_PACKAGE);
                    map.put("voPackage", PARENT_VO_PACKAGE);
                    map.put("queryDtoPackage", PARENT_Query_DTO_PACKAGE);
                    map.put("dtoIgnoreFields", DTO_IGNORE_FIELD);
                    this.setMap(map);
                }
            };
    
            // 如果模板引擎是 freemarker
            // String templatePath = "/templates/mapper.xml.vm.ftl";
            // 如果模板引擎是 velocity:
            // String templatePath = "/templates/mapper.xml.vm" ;
            //自定义输出配置
            List<FileOutConfig> focList = new ArrayList<>();
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig(TEMPLATE_MAPPER_XML_PATH) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "/" + MOUDLE_NAME + MAPPER_PATH + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
            //自定义生成类DTO/VO/QueryDOT
            focList.add(new FileOutConfig(TEMPLATE_DTO_PATH) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "\\" + MOUDLE_NAME + PARENT_DTO_PATH + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
                }
            });
            focList.add(new FileOutConfig(TEMPLATE_VO_PATH) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "\\" + MOUDLE_NAME + PARENT_VO_PATH + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
                }
            });
            focList.add(new FileOutConfig(TEMPLATE_QUERY_DTO_PATH) {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                    return projectPath + "\\" + MOUDLE_NAME + PARENT_Query_DTO_PATH + tableInfo.getEntityName() + "QueryDTO" + StringPool.DOT_JAVA;
                }
            });
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
    
            // 自定义模板
            TemplateConfig templateConfig = new TemplateConfig();
            //控制:不生java下成xml
            templateConfig.setXml(null);
            templateConfig.setEntity(null);
    
            // 配置自定义输出模板
            //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
            // templateConfig.setEntity("templates/entity2.java");
            templateConfig.setController(TEMPLATE_CONTROLLER_PATH);
            templateConfig.setService(TEMPLATE_SERVICE_PATH);
            templateConfig.setServiceImpl(TEMPLATE_SERVICEIMPL_PATH);
            templateConfig.setMapper(TEMPLATE_MAPPER_PATH);
            mpg.setTemplate(templateConfig);
    
            // 策略配置
            StrategyConfig sc = new StrategyConfig();
            sc.setNaming(NamingStrategy.underline_to_camel);
            sc.setColumnNaming(NamingStrategy.underline_to_camel);
            sc.setEntityLombokModel(true);//自动lombok
            sc.setRestControllerStyle(true);
            sc.setControllerMappingHyphenStyle(true);
            sc.setLogicDeleteFieldName("deleted");//设置逻辑删除
    
            //设置自动填充配置
            TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
            TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
            ArrayList<TableFill> tableFills = new ArrayList<>();
            tableFills.add(gmt_create);
            tableFills.add(gmt_modified);
            sc.setTableFillList(tableFills);
    
            //乐观锁
            sc.setVersionFieldName("version");
            sc.setRestControllerStyle(true);//驼峰命名
    
            sc.setTablePrefix(TABLE_PREFIX_ENTITY); //设置表名前缀
            sc.setInclude(tables);//表名,多个英文逗号分割
            mpg.setStrategy(sc);
    
            // 生成代码
            mpg.execute();
        }
    
        private static String apply(String t) {
            return TABLE_PREFIX + t;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253

    三、三层模板

    注意:不要更改模板的格式,模板格式已调成生成代码的样式!!!

    controller层

    controller.java.vm

    package ${package.Controller};
    
    import ${package.Service}.${table.serviceName};
    import ${cfg.dtoPackage}.${entity}DTO;
    import ${cfg.queryDtoPackage}.${entity}QueryDTO;
    import ${cfg.voPackage}.${entity}VO;
    import com.wl.cloud.core.dto.DataStoreDTO;
    import com.wl.cloud.core.dto.RestResultDTO;
    import io.swagger.v3.oas.annotations.Operation;
    import io.swagger.v3.oas.annotations.Parameter;
    import io.swagger.v3.oas.annotations.tags.Tag;
    import org.springdoc.api.annotations.ParameterObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.web.PageableDefault;
    import org.springframework.data.web.SortDefault;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    import java.util.Set;
    
    /**
     * $!{table.comment} 前端控制器
     *
     * @author ${author}
     * @since ${date}
     */
    #set($pathPrefix = "${cfg.requestPathPrefix}${table.entityPath}")
    @Tag(name = "$!{table.comment}", description = "${table.controllerName}")
    @Validated
    @CrossOrigin
    @RestController
    @RequestMapping("$pathPrefix")
    public class ${table.controllerName} {
    
        @Autowired
        private ${table.serviceName}  ${table.entityPath}Service;
    
        /**
         * 分页查询
         *
         * @param pageable
         * @return
         */
        @Operation(summary = "分页")
        @RequestMapping(value = "/page", method = {RequestMethod.POST, RequestMethod.GET})
        public RestResultDTO<DataStoreDTO<${entity}VO>>page(@ParameterObject @PageableDefault(sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable,
                                                            @ParameterObject ${entity}QueryDTO queryDto){
            return RestResultDTO.newSuccess(${table.entityPath}Service.page(pageable, queryDto));
        }
    
        /**
         * 列表查询
         *
         * @param sort
         * @return
         */
        @Operation(summary = "列表")
        @RequestMapping(value = "/list", method = {RequestMethod.POST, RequestMethod.GET})
        public RestResultDTO<List<${entity}VO>>list(@ParameterObject @SortDefault(sort = "createTime", direction = Sort.Direction.DESC) Sort sort,
                                                  @ParameterObject ${entity}QueryDTO queryDto){
            return RestResultDTO.newSuccess(${table.entityPath}Service.list(sort, queryDto));
        }
    
        /**
         * 保存
         *
         * @param dto
         * @return
         */
        @Operation(summary = "保存")
        @PostMapping("/save")
        public RestResultDTO<Void> save(@Validated @RequestBody ${entity}DTO dto){
            ${table.entityPath}Service.save(dto);
            return RestResultDTO.newSuccess();
        }
    
        /**
         * 修改
         *
         * @param dto
         * @return
         */
        @Operation(summary = "修改")
        @PostMapping(value = "/update")
        public RestResultDTO<Void> update(@Validated @RequestBody ${entity}DTO dto){
            ${table.entityPath}Service.update(dto);
            return RestResultDTO.newSuccess();
        }
    
        /**
         * 查询详情
         *
         * @param id
         * @return
         */
        @Operation(summary = "查询详情")
        @GetMapping("/get")
        public RestResultDTO<${entity}VO> get(@Parameter(description = "记录ID") @RequestParam String id){
            return RestResultDTO.newSuccess(${table.entityPath}Service.get(id));
        }
    
        /**
         * 删除
         *
         * @param ids
         * @return
         */
        @RequestMapping(value = "/delete", method = {RequestMethod.GET})
        public RestResultDTO<Void> delete(@RequestParam Set<String> ids){
            ${table.entityPath}Service.delete(ids);
            return RestResultDTO.newSuccess(null,"删除成功");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116

    service层

    service.java.vm

    package ${package.Service};
    
    import com.wl.cloud.core.dto.DataStoreDTO;
    import ${cfg.dtoPackage}.${entity}DTO;
    import ${cfg.queryDtoPackage}.${entity}QueryDTO;
    import ${cfg.voPackage}.${entity}VO;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.domain.Sort;
    
    import java.util.List;
    import java.util.Set;
    
    /**
     * $!{table.comment} 前端控制器
     *
     * @author ${author}
     * @since ${date}
     */
    public interface ${table.serviceName} {
    
        /**
         * 分页
         *
         * @param pageable
         * @param queryDto
         * @return
         */
        DataStoreDTO<${entity}VO> page(Pageable pageable, ${entity}QueryDTO queryDto);
    
        /**
         * 列表
         *
         * @param sort
         * @param queryDto
         * @return
         */
        List<${entity}VO> list(Sort sort, ${entity}QueryDTO queryDto);
    
        /**
         * 保存
         *
         * @param dto
         */
        void save(${entity}DTO dto);
    
        /**
         * 更新
         *
         * @param dto
         */
        void update(${entity}DTO dto);
    
        /**
         * 查看
         *
         * @param id
         * @return
         */
        ${entity}VO get(String id);
    
        /**
         * 删除
         *
         * @param ids
         */
        void delete(Set<String> ids);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    serviceImpl层

    serviceImpl.java.vm

    package ${package.ServiceImpl};
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.google.common.collect.Lists;
    import ${package.Mapper}.${entity}Mapper;
    import ${package.Entity}.${entity};
    import ${package.Service}.${entity}Service;
    import ${cfg.dtoPackage}.${entity}DTO;
    import ${cfg.queryDtoPackage}.${entity}QueryDTO;
    import ${cfg.voPackage}.${entity}VO;
    import com.wl.cloud.core.dto.DataStoreDTO;
    import com.wl.cloud.core.utils.PageUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.BeanUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.domain.Sort;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.util.Assert;
    
    import java.util.List;
    import java.util.Objects;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    /**
     * $!{table.comment} 服务实现类
     *
     * @author ${author}
     * @since ${date}
     */
    @Service
    public class ${table.serviceImplName} implements ${table.serviceName}{
    
        @Autowired
        private ${table.mapperName} ${table.entityPath}Mapper;
    
        @Transactional(readOnly = true)
        @Override
        public DataStoreDTO<${entity}VO> page(Pageable pageable, ${entity}QueryDTO queryDto) {
            QueryWrapper<${entity}> queryWrapper = this.buildQuery(queryDto);
            Page<${entity}> page = PageUtils.transferPage(pageable);
            Page<${entity}> result = this.${table.entityPath}Mapper.selectPage(page, queryWrapper);
            return new DataStoreDTO(result.getTotal(), this.transferVo(result.getRecords()));
        }
    
        @Transactional(readOnly = true)
        @Override
        public List<${entity}VO> list(Sort sort, ${entity}QueryDTO queryDto) {
            QueryWrapper<${entity}> queryWrapper = this.buildQuery(queryDto);
            PageUtils.transferSort(queryWrapper, sort);
            return this.transferVo(this.${table.entityPath}Mapper.selectList(queryWrapper));
        }
    
        @Transactional(rollbackFor = Exception.class)
        @Override
        public void save(${entity}DTO dto) {
            // TODO 唯一性字段校验
            dto.setId(null);
            ${table.entityPath}Mapper.insert(this.transferEntity(null, dto));
        }
    
        @Transactional(rollbackFor = Exception.class)
        @Override
        public void update(${entity}DTO dto) {
            Assert.hasText(dto.getId(), "id不能为空");
            // TODO 唯一性字段校验
            ${entity} entity = ${table.entityPath}Mapper.selectById(dto.getId());
            Assert.notNull(entity, "找不到id为 " + dto.getId() + " 的记录");
            ${table.entityPath}Mapper.updateById(this.transferEntity(entity, dto));
        }
    
        @Transactional(rollbackFor = Exception.class)
        @Override
        public void delete(Set<String> ids) {
            if (CollectionUtils.isNotEmpty(ids)) {
                ${table.entityPath}Mapper.deleteBatchIds(ids);
            }
        }
    
        @Transactional(readOnly = true)
        @Override
        public ${entity}VO get(String id) {
            Assert.hasText(id, "id不能为空");
            ${entity} entity = ${table.entityPath}Mapper.selectById(id);
            Assert.notNull(entity, "找不到id为 " + id + " 的记录");
            return this.transferVo(entity);
        }
    
        private QueryWrapper<${entity}> buildQuery(${entity}QueryDTO queryDto) {
            QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(queryDto)) {
                queryWrapper.lambda().eq(StringUtils.isNotBlank(queryDto.getId()), ${entity}::getId, queryDto.getId());
            }
            return queryWrapper;
        }
    
        private ${entity} transferEntity(${entity} entity, ${entity}DTO dto) {
            if (Objects.isNull(entity)) {
                entity = new ${entity}();
            }
            BeanUtils.copyProperties(dto, entity);
            return entity;
        }
    
        private List<${entity}VO> transferVo(List<${entity}> entities) {
            if (CollectionUtils.isEmpty(entities)) {
                return Lists.newArrayList();
            }
    
            List<${entity}VO> voList = entities.stream().map(entity -> {
            ${entity}VO vo = new ${entity}VO();
            BeanUtils.copyProperties(entity, vo);
                return vo;
            }).collect(Collectors.toList());
            return voList;
        }
    
        private ${entity}VO transferVo(${entity} entity) {
            if (Objects.isNull(entity)) {
                return null;
            }
            ${entity}VO vo = new ${entity}VO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130

    dao层

    mapper.java.vm

    package ${package.Mapper};
    
    import ${package.Entity}.${entity};
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import ${cfg.voPackage}.${entity}VO;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    /**
     * $!{table.comment} Mapper接口
     *
     * @author ${author}
     * @since ${date}
     */
    @Mapper
    public interface ${entity}Mapper extends BaseMapper<${entity}> {
        /**
        * 查询$!{table.comment}
        *
        * @return
        */
        List<${entity}VO> select${entity}List();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    mapper.xml文件

    mapper.xml.vm

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="${package.Mapper}.${table.mapperName}">
    
    #if(${enableCache})
        
        <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
    #end
    #if(${baseResultMap})
        
        <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
        #foreach($field in ${table.fields})
        #if(${field.keyFlag})##生成主键排在第一位
            <id column="${field.name}" property="${field.propertyName}" />
        #end
        #end
        #foreach($field in ${table.commonFields})##生成公共字段
        <result column="${field.name}" property="${field.propertyName}" />
        #end
        #foreach($field in ${table.fields})
        #if(!${field.keyFlag})##生成普通字段
            <result column="${field.name}" property="${field.propertyName}" />
        #end
        #end
        resultMap>
    #end
    #if(${baseColumnList})
        
        <sql id="Base_Column_List">
            #foreach($field in ${table.commonFields})
                ${field.columnName},
            #end
            ${table.fieldNames}
        sql>
    #end
    
        <select id="select${entity}List" resultType="${cfg.voPackage}.${entity}VO">
            select
            <include refid="${package.Mapper}.${table.mapperName}.Base_Column_List">include>
            from ${table.name}
            order by create_time desc limit 10;
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    四、新增类模板

    DTO

    dto.java.vm

    package ${cfg.dtoPackage};
    
    import com.wl.cloud.core.dto.AbstractBaseDTO;
    import io.swagger.v3.oas.annotations.media.Schema;
    import lombok.Data;
    
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.Size;
    
    import java.util.Date;
    
    /**
     * $!{table.comment}
     *
     * @author ${author}
     * @since ${date}
     */
    @Data
    @Schema(description = "$!{table.comment}")
    #set($ignoreFields = ${cfg.dtoIgnoreFields})
    public class ${entity}DTO extends AbstractBaseDTO {
    #if("$ignoreFields" == "")
        #foreach($field in ${table.fields})
            #if(${field.keyFlag})
                #set($keyPropertyName=${field.propertyName})
            #end
        #if("$!field.comment" != "")
        /**
         * ${field.comment}
         */
        #end
        @Schema(description = "$!{field.comment}")
        private ${field.propertyType} ${field.propertyName};
        #end
    #else
        #foreach($field in ${table.fields})
            #set($flag = "0")
            #foreach($ignoreName in ${cfg.dtoIgnoreFields.split(",")})
                #if("$ignoreName" == "${field.propertyName}")
                    #set($flag = "1")
                    #break
                #end
            #end
            #if($flag == "0")
                #if(${field.keyFlag})
                    #set($keyPropertyName=${field.propertyName})
                #end
        #if("$!field.comment" != "")
        /**
         * ${field.comment}
         */
        #end
        @Schema(description = "$!{field.comment} ${field.propertyName}")
        private ${field.propertyType} ${field.propertyName};
            #end
        #end
    #end
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    queryDTO类

    queryDto.java.vm

    package ${cfg.queryDtoPackage};
    
    import com.wl.cloud.core.dto.AbstractBaseDTO;
    import io.swagger.v3.oas.annotations.media.Schema;
    import lombok.Data;
    
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.Size;
    
    import java.util.Date;
    
    /**
     * $!{table.comment} 查询条件
     *
     * @author ${author}
     * @since ${date}
     */
    @Data
    @Schema(description = "$!{table.comment}")
    public class ${entity}QueryDTO extends AbstractBaseDTO {
    #foreach($field in ${table.fields})
        #if("$field.propertyName" == "id")
            #if(${field.keyFlag})
                #set($keyPropertyName=${field.propertyName})
            #end
            #if("$!field.comment" != "")
        /**
         * ${field.comment}
         */
        #end
        @Schema(description = "$!{field.comment}")
        private ${field.propertyType} ${field.propertyName};
        #end
    #end
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    VO类

    vo.java.vm

    package ${cfg.voPackage};
    
    import com.wl.cloud.core.dto.AbstractBaseDTO;
    import io.swagger.v3.oas.annotations.media.Schema;
    import lombok.Data;
    
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.Size;
    
    import java.util.Date;
    
    /**
     * $!{table.comment}
     *
     * @author ${author}
     * @since ${date}
     */
    @Data
    @Schema(description = "$!{table.comment}")
    public class ${entity}VO extends AbstractBaseDTO {
    #foreach($field in ${table.fields})
        #if(${field.keyFlag})
            #set($keyPropertyName=${field.propertyName})
        #end
        #if("$!field.comment" != "")
        /**
         * ${field.comment}
         */
        #end
        @Schema(description = "$!{field.comment}")
        private ${field.propertyType} ${field.propertyName};
    #end
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    五、截图展示

    在这里插入图片描述

    关注林哥,持续更新哦!!!★,°:.☆( ̄▽ ̄)/$:.°★ 。

  • 相关阅读:
    WPF 视频硬解码渲染播放(无空域)(支持4K、8K、高帧率视频)
    OpenCV笔记整理【模板匹配】
    前端vue-Taro框架中使用插件 ---pinyin 将城市树形分类
    数据结构-双向链表创建
    STM32实战总结:HAL之高级定时器
    【分享】影刀使用xpath捕获指定的元素
    unable to find valid certification path to requested target
    Nodejs+vue体育用品商城商品购物推荐系统_t81xg
    【已解决】ORA-01722: invalid number
    笔记本电脑重装系统win10教程-u盘装系统教程
  • 原文地址:https://blog.csdn.net/qq_45912025/article/details/132962770