Spring Boot与MyBatis-Plus:代码逆向生成指南

在Spring Boot项目中使用MyBatis-Plus进行代码逆向生成,可以通过MyBatis-Plus提供的代码生成器来快速生成实体类、Mapper接口、Service接口及其实现类等。以下是一个简单的示例步骤:

代码逆向生成 

1.添加依赖

pom.xml文件中添加MyBatis-Plus和代码生成器相关的依赖。

<!-- Spring Boot Starter Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MyBatis-Plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.7</version>
</dependency>
<!-- MyBatis-Plus Generator -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version> <!-- 使用合适的版本号 -->
</dependency>
<!-- MySQL 驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>

2.写代码生成器

创建一个Java类,用于配置和运行代码生成器。

public class CodeGenerator {

    // 你的数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/my_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";


    public static void main(String[] args) {
        FastAutoGenerator.create(URL, USERNAME, PASSWORD)
                .globalConfig(builder -> builder
                        .author("xiaochen")
                        .outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java")
                        .commentDate("yyyy-MM-dd")
                        .enableSwagger()
                )
                .packageConfig(builder -> builder
                        .parent("com.demo")
                        .entity("entity")
                        .controller("controller")
                        .service("service")
                        .serviceImpl("service.impl")
                        .mapper("mapper")
                        .xml("mapper.xml")

                )
                .strategyConfig(builder -> builder
                        .addInclude("user_test")
                        .entityBuilder()
                        .enableLombok()
                        
                )

                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }
}

3.运行代码生成器

运行CodeGenerator类的main方法,代码生成器将会根据配置生成相应的代码文件。

通过以上步骤,你可以快速生成MyBatis-Plus所需的实体类、Mapper接口、Service接口及其实现类等代码,大大提高开发效率。

续:

当然也可以自定义controller,配置如下:

1.修改controller模板 

将其放在 resources 下的 templates 目录下

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 ${package.Entity}.${entity};
<#if generateService>
import ${package.Service}.${table.serviceName};
</#if>
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;

/**
 * <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} {
</#if>
    @Autowired
    private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first};

    /**
     * 查询所有
     */
    @GetMapping
    public List<${entity}> getAll() {
        return ${(table.serviceName?substring(1))?uncap_first}.list();
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public  ${entity} getById(@PathVariable Long id) {
        return ${(table.serviceName?substring(1))?uncap_first}.getById(id);
    }



    /**
     * 添加
     */
    @PostMapping
    public boolean add(@RequestBody ${entity} ${entity?uncap_first}) {
        return ${(table.serviceName?substring(1))?uncap_first}.save(${entity?uncap_first});
    }

    /**
     * 修改
     */
    @PutMapping("/{id}")
    public boolean update(@PathVariable Integer id, @RequestBody  ${entity} ${entity?uncap_first}) {
        ${entity?uncap_first}.setId(id);
        return ${(table.serviceName?substring(1))?uncap_first}.updateById(${entity?uncap_first});
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return ${(table.serviceName?substring(1))?uncap_first}.removeById(id);
    }
}
</#if>

2.在strategyConfig配置中添加如下代码

.controllerBuilder().enableRestStyle().template("templates/controller.java")

 3.测试:

生成效果如下:


/**
 * <p>
 *  前端 控制器
 * </p>
 *
 * @author xiaochen
 * @since 2024-07-05
 */
@RestController
@RequestMapping("/userTest")
public class UserTestController {
    @Autowired
    private IUserTestService userTestService;
    /**
     * 查询所有
     */
    @GetMapping
    public List<UserTest> getAll() {
        return userTestService.list();
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public  UserTest getById(@PathVariable Long id) {
        return userTestService.getById(id);
    }
    /**
     * 添加
     */
    @PostMapping
    public boolean add(@RequestBody UserTest userTest) {
        return userTestService.save(userTest);
    }
    /**
     * 修改
     */
    @PutMapping("/{id}")
    public boolean update(@PathVariable Integer id, @RequestBody  UserTest userTest) {
        userTest.setId(id);
        return userTestService.updateById(userTest);
    }
    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return userTestService.removeById(id);
    }
}

 

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值