MyBatisPlus-自动生成代码

前端之家收集整理的这篇文章主要介绍了MyBatisPlus-自动生成代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller

一、依赖

1、pom.xml 导入 MyBatis Plus Generator

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>

Velocity(默认)、Freemarker、Beetl

数据库中的表

二、启动类

package com.md.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.Scanner;

/**
 * @author md
 * @Desc
 * @date 2020/10/26 22:13
 */
public class main {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        //创建generator对象
        AutoGenerator autoGenerator = new AutoGenerator();

        //数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MysqL);
        dataSourceConfig.setUrl("jdbc:MysqL://localhost:3306/springboot?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        dataSourceConfig.setDriverName("com.MysqL.cj.jdbc.Driver");
        autoGenerator.setDataSource(dataSourceConfig);


        //全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        // 工程的绝对路径+下面的目录,根据自己的路径修改
        globalConfig.setOutputDir(System.getProperty("user.dir")+"/02-auto/src/main/java");
        globalConfig.setOpen(false);
        globalConfig.setAuthor("md");
        globalConfig.setServiceName("%sService");
        autoGenerator.setGlobalConfig(globalConfig);


        //包信息
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.md.mybatisplus");
        // 生成的module
        packageConfig.setModuleName(scanner("模块名:"));

        packageConfig.setController("controller");
        packageConfig.setService("service");
        packageConfig.setServiceImpl("service.impl");
        packageConfig.setMapper("mapper");
        packageConfig.setEntity("entity");
        autoGenerator.setPackageInfo(packageConfig);


        //配置策略
        StrategyConfig strategyConfig = new StrategyConfig();
        // 自动添加Lombok注解
        strategyConfig.setEntityLombokModel(true);
        // 数据库中的下划线改驼峰
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        // 可以指定表名
        strategyConfig.setInclude(scanner("表名,多个英文逗号分割").split(","));
        autoGenerator.setStrategy(strategyConfig);


        autoGenerator.execute();
    }
}

这样就基本生成,默认有很多方法,可以直接使用

三、测试

1. Application

加入mapper

package com.md.mybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(value = "com.md.mybatisplus.user.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

2. 主配置文件

spring.datasource.driver-class-name=com.MysqL.cj.jdbc.Driver
spring.datasource.url=jdbc:MysqL://localhost:3306/springboot?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8

spring.datasource.username=root
spring.datasource.password=123456


# 专门用于打印日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl



#thymeleaf 模版前缀,默认可以不写
spring.thymeleaf.prefix=classpath:/templates/

#thymeleaf 模版后缀,默认可以不写
spring.thymeleaf.suffix=.html

3. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.md.mybatisplus</groupId>
    <artifactId>02-auto</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>02-auto</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>MysqL</groupId>
            <artifactId>MysqL-connector-java</artifactId>
            <scope>5.1.9</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

        <!--自动生成-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <!--自动生成的模板-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4. UserController

package com.md.mybatisplus.user.controller;


import com.md.mybatisplus.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author md
 * @since 2020-10-26
 */
@Controller
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        // 自动生成方法,直接使用,查询数据库中的全部数据
        mv.addObject("users",userService.list());

        return mv;
    }
}


5. index

templates下的index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<table>
    <tr th:each="user:${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.age}"></td>
    </tr>
</table>

</body>
</html>

此时访问页面就可以访问到数据库中的数据

猜你在找的Mybatis相关文章