SpringBoot集成MyBaits-plus使用方法

前言

MyBaits-plus提供了代码生成器,通过编写代码生成类,执行该方法,即可自动生成相应模板文件。先看一下效果,再来详细解释怎么用MyBaits-plus。

这个包下的所有文件都是自动生成的。
在这里插入图片描述

一、导入依赖

这里导入freemarker是因为需要用到模板引擎来生成文件,也可以用其他模板引擎。

<!--mp-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--mp代码生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.2.0</version>
</dependency>

二、添加MyBatis配置

### MyBatis配置
mybatis.mapper-locations=classpath:/mappers/ *Mapper.xml
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/fitness_system?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=用户名
spring.datasource.password=密码

三、编写代码并运行



/**
 * @ClassName CodeGenerator
 * @Description 控制台输入表名自动生成相应文件
 * @Author yuisama
 * @Date 2021/4/15 16:08
 */


public class CodeGenerator {

    public static String scanner(String table){
        Scanner scanner  = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入"+table+":");
        System.out.println(help.toString());
        if(scanner.hasNext()){
            String result = scanner.next();
            if(StringUtils.isNotBlank(result)) {
                return result;
            }
        }
        throw new MybatisPlusException("请输入正确的表名!");
    }

    public static void main(String[] args) {
        AutoGenerator autoGenerator = new AutoGenerator();

        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = "F:\\JavaProject\\fitness_system";
        globalConfig.setOutputDir(projectPath+"\\src\\main\\java");
        globalConfig.setAuthor("na.zhao");
        globalConfig.setOpen(true);
        globalConfig.setFileOverride(true);
        globalConfig.setDateType(DateType.TIME_PACK);
        globalConfig.setIdType(IdType.AUTO);
        autoGenerator.setGlobalConfig(globalConfig);

        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/fitness_system?serverTimezone=GMT%2B8");
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("root");
        autoGenerator.setDataSource(dataSourceConfig);

        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setModuleName(scanner("模块名"));
        packageConfig.setParent("com.vip.zn.fitness_system");
        autoGenerator.setPackageInfo(packageConfig);

        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                //TODO nothing
            }
        };

        String templatePath = "/templates/mapper.xml.ftl";
        List<FileOutConfig> fileOutConfigList = new ArrayList<>();
        fileOutConfigList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper/" + packageConfig.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        injectionConfig.setFileOutConfigList(fileOutConfigList);
        autoGenerator.setCfg(injectionConfig);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        autoGenerator.setTemplate(templateConfig);

        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        strategyConfig.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategyConfig.setControllerMappingHyphenStyle(true);
        strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");
        autoGenerator.setStrategy(strategyConfig);
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        autoGenerator.execute();

    }


}

如果代码运行正常的话,目录下就会生成图一展示的文件啦~

四、再验证一下

在UserController中编写如下代码

@RestController
@RequestMapping("/db/user")
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @RequestMapping("/{id}")
    public Object selectByUserId(@PathVariable("id")Long id){
        return userService.getById(id);
    }
}

启动项目,在浏览器中输入http://localhost:8080/db/user/1,, 就可以看到如下效果啦,证明集成mybaits-plus成功啦~
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值