springboot使用MP代码生成器并配置controller模板

第一步:导入MP依赖

<!--        MP-->
        <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>
<!--        默认的代码生成器 可以生成controller模板-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

第二步:MP代码生成器配置

修改前:

修改后:

package com.rong.config;

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) {

        FastAutoGenerator.create("jdbc:mysql://localhost:3306/rong?serverTimezone=GMT%2b8", "root", "123456")
                .globalConfig(builder -> {
                    builder.author("荣") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("D:\\ideaPractice\\newPractice\\drugspringboot\\drugsystem\\src\\main\\java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.rong") // 设置父包名
                            .moduleName(null) // 设置父包模块名(不设置controller上面路径只有user)
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\\ideaPractice\\newPractice\\drugspringboot\\drugsystem\\src\\main\\resources\\mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.controllerBuilder().enableHyphenStyle();
                    builder.controllerBuilder().enableRestStyle();
                    // 设置需要生成的表名
                    builder.addInclude("sys_user")
                    .addTablePrefix("t_", "sys_"); // 设置过滤表前缀
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }

}

如果不需要设置controller自己的模板,以上步骤就可以了。

第三步:配置controller模板

controller模板语法配置:

package ${package.Controller};


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

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};


#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);
        }

        @PostMapping("/del/batch")
        public boolean deleteBatch(@RequestBody List<Integer> ids) {
            return ${table.entityPath}Service.removeByIds(ids);
        }

        @GetMapping
        public List<${entity}> findAll() {
            return ${table.entityPath}Service.list();
        }

        @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<${entity}> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("id");
            return ${table.entityPath}Service.page(new Page<>(pageNum, pageSize), queryWrapper);
        }


}

#end

配置完在重新启动代码生成器,controller效果如下:

package com.rong.controller;


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

import com.rong.entity.User;
import com.rong.service.IUserService;


import org.springframework.stereotype.Controller;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 荣
 * @since 2023-11-26
 */
@RestController
@RequestMapping("/user")
public class UserController {

        @Resource
        private IUserService userService;

// 新增或者更新
@PostMapping
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.removeByIds(ids);
        }

        @GetMapping
        public List<User> findAll() {
            return userService.list();
        }

        @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<>();
            queryWrapper.orderByDesc("id");
            return userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        }


}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你好!要配置 Spring BootMyBatis-Plus(简称 MP), 需要进行以下步骤: 1. 在 pom.xml 文件中添加 MyBatis-Plus 的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> ``` 2. 在 application.properties/application.yml 文件中配置数据库连接信息,例如: ```yaml spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类和对应的 Mapper 接口。实体类使用 `@TableName` 注解指定对应的数据库表名,Mapper 接口使用 `@Mapper` 注解标识。 4. 在启动类上添加 `@MapperScan` 注解来扫描 Mapper 接口所在的包路径,例如: ```java @SpringBootApplication @MapperScan("com.example.mapper") public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } ``` 5. 如果需要使用 MyBatis-Plus 的自动填充功能,可以创建一个实现了 `MetaObjectHandler` 接口的类,并在该类上添加 `@Component` 注解,如: ```java @Component public class MyMetaObjectHandler implements MetaObjectHandler { // 实现相应的方法 } ``` 这样就完成了 Spring Boot 配置 MyBatis-Plus 的基本步骤。你可以根据具体需求进行更多的配置使用。希望对你有帮助!如果你还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值