首页 > 其他分享 >mybatis-plus代码生成器使用

mybatis-plus代码生成器使用

时间:2023-03-19 14:55:14浏览次数:52  
标签:代码生成 return public plus table mybatis import com id

以下仅供自己个人学习使用

  1. 去mybatis-plus官网

https://baomidou.com/pages/779a6e/

  1. 引入相关的pom.xml依赖
  <!--        代码生成器-->
        <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>

image

  1. 创建utils目录,新建CodeGenerator类(可以根据自己的需要放在其他的地方)

image

  1. 复制官网的代码生成器代码到你创建的CodeGenerator类中(下面是本人使用的,记得根据自己需求来进行修改)
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;

import java.util.Collections;

/**
 * 代码生成器
 */
public class CodeGenerator {
    public static void main(String[] args) {
        generate();
    }
    private static void generate(){
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8", "root", "123456")
                .globalConfig(builder -> {
                    builder.author("el") // 设置作者
                            //.enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("C:\\Users\\萧山何\\eclipse-workspace\\Desktop\\springboot\\src\\main\\java\\"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.el.springboot") // 设置父包名
                            .moduleName(null) // 设置父包模块名 路径
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "C:\\Users\\萧山何\\eclipse-workspace\\Desktop\\springboot\\src\\main\\resources\\mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.entityBuilder().enableLombok();//Lombok表达式
                    builder.mapperBuilder().enableMapperAnnotation().build();//加mapper注解
                    builder.controllerBuilder().enableHyphenStyle()  // 开启驼峰转连字符
                            .enableRestStyle();  // 开启生成@RestController 控制器
                    builder.addInclude("sys_user") // 设置需要生成的表名
                            .addTablePrefix("t_", "sys_"); // 设置过滤表前缀
                })
                //.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

  1. 运行的效果

image

6. 配置controller模板

6.1 在导入的maven依赖里面找到这个

image

6.2 复制到resources目录的templates下

image

6.3 然后根据自己需求进行模板配置
下面这个是简单的增删改查模板

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

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

        //新增或更新
        @PostMapping
        public Boolean save(@RequestBody ${entity} ${table.entityPath}) {
            return ${table.entityPath}Service.saveOrUpdate(${table.entityPath});
        }
        //删除
        @DeleteMapping("/{id}")
        public Boolean delete(@PathVariable Integer id) {
            return ${table.entityPath}Service.removeById(id);
        }
        //查询列表
        @GetMapping
        public List<${entity}> findAll() {
            return ${table.entityPath}Service.list();
        }
        //根据ID查询
        @GetMapping("/{id}")
        public ${entity} findOne(@PathVariable Integer id) {
            return ${table.entityPath}Service.getById(id);
        }
        //分页查询
        @GetMapping("/page")
        public Page<${entity}> findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
            return ${table.entityPath}Service.page(new Page<>(pageNum, pageSize),queryWrapper);
        }
}

#end

6.4 运行成功之后你的Usercontroller得到的效果:

package com.el.springboot.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
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.el.springboot.service.IUserService;
import com.el.springboot.entity.User;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author el
 * @since 2023-03-19
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    //新增或更新
    @PostMapping("/save")
    public Boolean save(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

    //删除
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }

    /**
     * 批量删除
     */
    @PostMapping("/del/batch")
    public Boolean deleteBatch(@RequestBody List<Integer> ids) {
        return userService.removeBatchByIds(ids);
    }

    //查询列表
    @GetMapping
    public List<User> findAll() {
        return userService.list();
    }

    //根据ID查询
    @GetMapping("/{id}")
    public User findOne(@PathVariable Integer id) {
        return userService.getById(id);
    }

    //分页查询
    @GetMapping("/page")
    public Page<User> findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize
    ) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        return userService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }
}


  • 番外:
  1. 自定义的东西尽量自己添加(例如:下面的分页查询条件和批量删除有需要的小伙伴可以复制使用)
package com.el.springboot.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
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.el.springboot.service.IUserService;
import com.el.springboot.entity.User;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author el
 * @since 2023-03-19
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    //新增或更新
    @PostMapping("/save")
    public Boolean save(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

    //删除
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }

    /**
     * 批量删除
     */
    @PostMapping("/del/batch")
    public Boolean deleteBatch(@RequestBody List<Integer> ids) {
        return userService.removeBatchByIds(ids);
    }

    //查询列表
    @GetMapping
    public List<User> findAll() {
        return userService.list();
    }

    //根据ID查询
    @GetMapping("/{id}")
    public User findOne(@PathVariable Integer id) {
        return userService.getById(id);
    }

    //分页查询
    @GetMapping("/page")
    public Page<User> findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String email,
                               @RequestParam(defaultValue = "") String address
    ) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
            queryWrapper.like("username", username);
        }
        if (!"".equals(email)) {
            queryWrapper.like("email", email);
        }
        if (!"".equals(address)) {
            queryWrapper.like("address", address);
        }
        queryWrapper.orderByDesc("id");
        return userService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }
}


标签:代码生成,return,public,plus,table,mybatis,import,com,id
From: https://www.cnblogs.com/Amyel/p/17233060.html

相关文章