在SpringBoot使用MyBatis-Plus代码生成器

文章目录

前言

一、引入依赖

二、使用步骤

1.创建一个类(例如CodeGenerator)

2.编辑生成模板

三、一键生成代码

 结尾


前言

在SpringBoot中,通过引入MyBatis-Plus 实现数据库代码生成器,我还写好了一些模板方法,可一键生成。

注意

适用版本:mybatis-plus-generator 3.5.1 及其以上版本

一、引入依赖

在pom.xml中引入代码生成器、以及代码生成器中默认使用的velocity引擎

<!-- 代码生成器 -->
<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>

二、使用步骤

1.创建一个类(例如CodeGenerator)

把以下代码放到一个方法中。

FastAutoGenerator.create("url", "username", "password")
    .globalConfig(builder -> {
        builder.author("baomidou") // 设置作者
            .enableSwagger() // 开启 swagger 模式
            .fileOverride() // 覆盖已生成文件
            .outputDir("D://"); // 指定输出目录
    })
    .packageConfig(builder -> {
        builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
            .moduleName("system") // 设置父包模块名
            .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
    })
    .strategyConfig(builder -> {
        builder.addInclude("t_simple") // 设置需要生成的表名
            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
    })
    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
    .execute();

我的代码如下(示例):

默认使用的Velocity引擎模板,所以就把使用Freemarker代码注释掉了

2.编辑生成模板

官方的模板位置如下:

将controller.java.vm复制到resources/templates下

 可直接使用默认没有功能的模板,也可复制我的,编写了一些增删改查、分页的模板

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 ${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) {
       return ${table.entityPath}Service.page(new Page<>(pageNum, pageSize));
    }
}

#end

此处的增删改查调用了mybatis-plus的功能,不懂的小伙伴可以配置学习一下

三、一键生成代码

只需在CodeGenerator.java中运行一下代码

 

前端控制器UserController、数据库实体类User、service、UserMapper就一件生成好啦。

 我们自定义的功能也在UserController中啦。

 结尾

代码生成器可以一键省去我们一半花在创建和写SQL代码的时间,不过平时小伙伴不急着做项目,也可以手动写写,提高SQL语言能力。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Spring Boot整合MyBatis-Plus可以通过使用代码生成器来自动生成CRUD代码。下面是使用步骤: 1. 首先,在pom.xml文件中添加MyBatis-Plus和相关依赖: ```xml <!-- MyBatis-Plus依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> <!-- MyBatis-Plus代码生成器依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>最新版本号</version> </dependency> ``` 2. 创建一个配置类来配置代码生成器: ```java @Configuration public class MyBatisPlusConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${mybatis-plus.package}") private String packageName; @Value("${mybatis-plus.author}") private String author; @Value("${mybatis-plus.table-prefix}") private String tablePrefix; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName(driverClassName); return dataSource; } @Bean public GlobalConfig globalConfig() { GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setAuthor(author); globalConfig.setOpen(false); return globalConfig; } @Bean public DataSourceConfig dataSourceConfig() { DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MYSQL); dataSourceConfig.setDriverName(driverClassName); dataSourceConfig.setUsername(username); dataSourceConfig.setPassword(password); dataSourceConfig.setUrl(url); return dataSourceConfig; } @Bean public PackageConfig packageConfig() { PackageConfig packageConfig = new PackageConfig(); packageConfig.setParent(packageName); packageConfig.setEntity("entity"); packageConfig.setMapper("mapper"); packageConfig.setService("service"); packageConfig.setServiceImpl("service.impl"); packageConfig.setController("controller"); return packageConfig; } @Bean public StrategyConfig strategyConfig() { StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig.setEntityColumnConstant(true); strategyConfig.setEntityLombokModel(true); strategyConfig.setNaming(NamingStrategy.underline_to_camel); strategyConfig.setInclude("表名1", "表名2"); // 生成指定的表 strategyConfig.setRestControllerStyle(true); strategyConfig.setTablePrefix(tablePrefix); // 设置表前缀 return strategyConfig; } @Bean public TemplateConfig templateConfig() { TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setController(null); // 不生成controller层 return templateConfig; } @Bean public InjectionConfig injectionConfig() { Map<String, Object> map = new HashMap<>(); return new InjectionConfig() { @Override public void initMap() { this.setMap(map); } }; } @Bean public AutoGenerator autoGenerator() { AutoGenerator autoGenerator = new AutoGenerator(); autoGenerator.setGlobalConfig(globalConfig()); autoGenerator.setDataSource(dataSourceConfig()); autoGenerator.setPackageInfo(packageConfig()); autoGenerator.setStrategy(strategyConfig()); autoGenerator.setTemplate(templateConfig()); autoGenerator.setCfg(injectionConfig()); return autoGenerator; } } ``` 3. 在application.properties或application.yml文件中配置相关信息: ```properties # 数据源配置 spring.datasource.url=数据库URL spring.datasource.username=数据库用户名 spring.datasource.password=数据库密码 spring.datasource.driver-class-name=数据库驱动类名 # MyBatis-Plus配置 mybatis-plus.package=你的包路径 mybatis-plus.author=代码作者名 mybatis-plus.table-prefix=表前缀 ``` 4. 创建一个启动类,添加@SpringBootApplication和@EnableAutoConfiguration注解,并在main方法中调用代码生成器生成代码: ```java @SpringBootApplication @EnableAutoConfiguration public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); // 调用代码生成器生成代码 ApplicationContext context = SpringApplication.run(MyApplication.class, args); AutoGenerator autoGenerator = context.getBean(AutoGenerator.class); autoGenerator.execute(); } } ``` 5. 运行启动类,执行代码生成器。生成的代码将包含实体类、Mapper接口、Service接口、Service实现类和Controller类。 这样就能根据数据库表自动生成CRUD代码了。如果需要生成其他的代码,可以根据需要配置生成器相应的参数和模板。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Phils程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值