Spring Boot整合Mybatis-Plus代码生成器、VM模板

1、pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.9</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.stu</groupId>
    <artifactId>study</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>study</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>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>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</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>




    </dependencies>



</project>

2、CodeGenerator.java

package com.stu.study.utils;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;

import java.util.Collections;

/******************************
 * 用途说明:
 * 作者姓名: 更多干货 公众号 技术从南指到北
 * 创建时间: 2023-02-27 21:26
 ******************************/
public class CodeGenerator {

    public static void main(String[] args) {
        generate();
    }

    private static void generate(){

        String projectPath = System.getProperty("user.dir");

        FastAutoGenerator.create("jdbc:mysql://localhost:3306/2023Java?serverTimezone=GMT%2b8",
                "root", "study")
                .globalConfig(builder -> {
                    builder.author("技术从南指到北") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir(projectPath + "/src/main/java"); // 指定输出目录"E:\\20221025_work\\2023JAVA\\src\\main\\java\\"
                })
                .packageConfig(builder -> {
                    builder.parent("com.stu.study") // 设置父包名
                            .moduleName("") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml,
                                    projectPath + "/src/main/resources/mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.entityBuilder().enableLombok();
                    builder.mapperBuilder().enableMapperAnnotation().build();
                    builder.controllerBuilder().enableHyphenStyle()  // 开启驼峰转连字符
                            .enableRestStyle();  // 开启生成@RestController 控制器
                    builder.addInclude("sys_role") // 设置需要生成的表名
                            .addTablePrefix("sys_"); // 设置过滤表前缀
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }
}

3、controller.java.vm

注意目录,在resources下的templats文件夹下创建controller.java.vm文件

package ${package.Controller};

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};

#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/******************************
 * 用途说明: $!{table.comment}
 * 作者姓名: 更多干货 公众号 技术从南指到北
 * 创建时间: ${date}
 ******************************/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end

#else
    #if(${superControllerClass})
    public class ${table.controllerName} extends ${superControllerClass} {
    #else
    public class ${table.controllerName} {
    #end
    @Resource
    private ${table.serviceName} ${table.entityPath}Service;

    /******************************
    * 用途说明: $!{table.comment}
    * 作者姓名: 更多干货  公众号  技术从南指到北
    * 创建时间: ${date}
    ******************************/
    @PostMapping
    public boolean save(@RequestBody ${entity} ${table.entityPath}){
        return ${table.entityPath}Service.saveOrUpdate(${table.entityPath});
    }

    /******************************
     * 用途说明: $!{table.comment}
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: ${date}
     ******************************/
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id){
        return ${table.entityPath}Service.removeById(id);
    }

    /******************************
     * 用途说明: $!{table.comment}
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: ${date}
     ******************************/
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids){
        return ${table.entityPath}Service.removeByIds(ids);
    }

    /******************************
     * 用途说明: $!{table.comment}
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: ${date}
     ******************************/
    @GetMapping
    public List<${entity}> findAll(){
        return ${table.entityPath}Service.list();
    }

    /******************************
     * 用途说明: $!{table.comment}
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: ${date}
     ******************************/
    @GetMapping("/{id}")
    public ${entity} findOne(@PathVariable Integer id){
        return ${table.entityPath}Service.getById(id);
    }

    /******************************
     * 用途说明: $!{table.comment}
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: ${date}
     ******************************/
    @GetMapping("/page")
    public Page<${entity}> findPage(@RequestParam Integer pageNum,
    @RequestParam Integer pageSize){
        QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return ${table.entityPath}Service.page(new Page<>(pageNum,pageSize),queryWrapper);
    }
 }
#end

4、mybatis puls配置类

package com.stu.study.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/******************************
 * 用途说明:
 * 作者姓名: Administrator
 * 创建时间: 2023-02-09 22:02
 ******************************/
@Configuration
@MapperScan("com.stu.**.mapper")
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }
}

5、目录结构

6、点击运行main方法,生成的代码如下

controller

package com.stu.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stu.study.service.IRoleService;
import com.stu.study.entity.Role;

import org.springframework.web.bind.annotation.RestController;

/******************************
 * 用途说明: 
 * 作者姓名: 更多干货 公众号 技术从南指到北
 * 创建时间: 2023-02-27
 ******************************/
@RestController
@RequestMapping("//role")
        public class RoleController {
        @Resource
    private IRoleService roleService;

    /******************************
    * 用途说明: 
    * 作者姓名: 更多干货  公众号  技术从南指到北
    * 创建时间: 2023-02-27
    ******************************/
    @PostMapping
    public boolean save(@RequestBody Role role){
        return roleService.saveOrUpdate(role);
    }

    /******************************
     * 用途说明: 
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: 2023-02-27
     ******************************/
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id){
        return roleService.removeById(id);
    }

    /******************************
     * 用途说明: 
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: 2023-02-27
     ******************************/
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids){
        return roleService.removeByIds(ids);
    }

    /******************************
     * 用途说明: 
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: 2023-02-27
     ******************************/
    @GetMapping
    public List<Role> findAll(){
        return roleService.list();
    }

    /******************************
     * 用途说明: 
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: 2023-02-27
     ******************************/
    @GetMapping("/{id}")
    public Role findOne(@PathVariable Integer id){
        return roleService.getById(id);
    }

    /******************************
     * 用途说明: 
     * 作者姓名: 更多干货  公众号  技术从南指到北
     * 创建时间: 2023-02-27
     ******************************/
    @GetMapping("/page")
    public Page<Role> findPage(@RequestParam Integer pageNum,
    @RequestParam Integer pageSize){
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return roleService.page(new Page<>(pageNum,pageSize),queryWrapper);
    }
 }

entity

package com.stu.study.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

/**
 * <p>
 * 
 * </p>
 *
 * @author 技术从南指到北
 * @since 2023-02-27
 */
@Getter
@Setter
  @TableName("sys_role")
@ApiModel(value = "Role对象", description = "")
public class Role implements Serializable {

    private static final long serialVersionUID = 1L;

      @ApiModelProperty("id")
        @TableId(value = "id", type = IdType.AUTO)
      private Integer id;

      @ApiModelProperty("名称")
      private String name;

      @ApiModelProperty("描述")
      private String description;

      @ApiModelProperty("唯一标识")
      private String flag;


}

service接口

package com.stu.study.service;

import com.stu.study.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author 技术从南指到北
 * @since 2023-02-27
 */
public interface IRoleService extends IService<Role> {

}

service实现类

package com.stu.study.service.impl;

import com.stu.study.entity.Role;
import com.stu.study.mapper.RoleMapper;
import com.stu.study.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 技术从南指到北
 * @since 2023-02-27
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

}

mapper接口,因为上边的配置类,配置了加了@MapperScan("com.stu.**.mapper"),所以mapper接口可以省略@Mapper注解

package com.stu.study.mapper;

import com.stu.study.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author 技术从南指到北
 * @since 2023-02-27
 */
//@Mapper
public interface RoleMapper extends BaseMapper<Role> {

}

mapper.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.stu.study.mapper.RoleMapper">

</mapper>

 

posted @ 2023-02-27 23:59  程序员小明1024  阅读(443)  评论(0编辑  收藏  举报