JavaWeb练习之使用Mybatis Plus

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_32377671/article/details/82750185

Mybatis-Plus使用练习


这里使用的是2.3的版本,因为公司项目中用的就是2.3的版本。所以就没再去瞎捅咕(Mybatis-Plus2.x的说明文档)。具体作用就是用来快速生成文件模板的工具,相当于一键生成Controller、Service、Mapper和pojo类而且还支持lombok(这个只需要在配置中开启就行,当然别忘了添加依赖),可以说是相当的方便了。

Pom.xml配置相关的依赖


这里跟Mybatis-Plus有关系的只有这三项。

  1. mybatis-plus-boot-starter ➡️ Mybatis-Plus的依赖
  2. velocity ➡️ 用来生成模板
  3. lombok ➡️ 用来简化实体类(实际作用与Kotlin 的 data class 基本一致)
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lyan</groupId>
    <artifactId>web_note</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>web_note</name>
    <description>study,test,note</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <mybatis_plus.version>2.3</mybatis_plus.version>
        <velocity.version>1.7</velocity.version>
        <lombok.version>1.18.0</lombok.version>
        <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>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis_plus.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>${velocity.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

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


</project>

创建一个可以运行的类

使用Main方法还是单元测试都行,只要能运行就行。这里我将生成的文件路径直接设到了项目中。代码有点长,根据步骤也写了注释,基本上还是很好理解的,这里就不分步骤了:

package com.lyan.web_note;


import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisGeneratorTest {

//    private static final String WORK_PATH = "E:/Work/Java/MineWebTest/src/main";//项目工程目录
    private static final String WORK_PATH = "/Users/apple/MineFile/mine2018/web/MineWebTest/src/main";//项目工程目录
    private static final String OUTPUT_DIR = WORK_PATH + "/java/";//功能文件的输出路径(mvc)
    private static final String MAPPER_DIR = WORK_PATH + "/resources/mapper/";//映射文件的输出路径(mapper.xml)
    private static final String SQL_PATH = "localhost:3306";//数据库连接地址
    private static final String SQL_NAME = "test";//数据库名称
    private static final String TABLE_NAME = "week_day";//表名
    private static final String PARENT_NAME = "com.lyan.web_note.modules";//父包路径
    private static final String MODULE_NAME = TABLE_NAME;//模型的的包名

    @Test
    public void createWebFile() {

        AutoGenerator autoGenerator = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(OUTPUT_DIR);//创建的文件输出路径
        globalConfig.setFileOverride(true);//文件覆盖
        globalConfig.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        globalConfig.setEnableCache(false);// XML 二级缓存
        globalConfig.setBaseResultMap(true);// XML ResultMap
        globalConfig.setBaseColumnList(false);// XML columList
        globalConfig.setAuthor("Lyan");//作者

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                return super.processTypeConvert(fieldType);
            }
        });
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        dataSourceConfig.setUrl("jdbc:mysql://" + SQL_PATH + "/" + SQL_NAME + "?useUnicode=true&characterEncoding=utf8&useSSL=false");

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setInclude(TABLE_NAME);// 生成该表相关的文件
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategyConfig.setRestControllerStyle(true);//使用RestController
        strategyConfig.setEntityLombokModel(true);//使用插件生成实体类

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent(PARENT_NAME);
        packageConfig.setModuleName(MODULE_NAME);
        packageConfig.setController("controller");
        packageConfig.setEntity("entity");

        //对生成的模板进行设置
        setTemplateOpinion(autoGenerator);
        // 生成模板文件
        autoGenerator.setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig).execute();
    }

    private static void setTemplateOpinion(AutoGenerator autoGenerator) {

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        List<FileOutConfig> fileOutConfigList = new ArrayList<>();
        //修改Mapper.xml文件生成的位置
        fileOutConfigList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return MAPPER_DIR + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        injectionConfig.setFileOutConfigList(fileOutConfigList);
        autoGenerator.setCfg(injectionConfig);
        //关闭默认文件的生成
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        templateConfig.setMapper("/vm/mapper.java.vm");
        templateConfig.setController("/vm/controller.java.vm");
        templateConfig.setService("/vm/service.java.vm");
        templateConfig.setServiceImpl("/vm/serviceImpl.java.vm");
        templateConfig.setEntity("/vm/entity.java.vm");

        autoGenerator.setTemplate(templateConfig);
    }

}

下面的就是准备的测试数据表。
  
在这里插入图片描述
  
  运行@Test方法,生成如下的目录结构。每个文件都生成到了目标路径中。
    
在这里插入图片描述

测试运行

配置application.yml。

spring:
  #配置数据源
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: 123456
  #配置模板
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    cache: false
    encoding: UTF-8
server:
  port: 8080
  servlet:
    # 项目名称
    context-path: /webNote
#mybatis
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 2
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    # SQL 解析缓存,开启后多租户 @SqlParser 注解生效
    sql-parser-cache: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false

注意一下给Mapper的接口映射文件配置上@Mapper,这样就不用配置@MapperSpan了。我这里偷了个懒直接修改的模板文件,直接在模板中加上了@Mapper。

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

/**
 * $!{table.comment} Mapper 接口
 * @author ${author}
 * @since ${date}
 */
@Mapper
@Component
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}

最后在WeekDayController中写一个接口,将表中的数据以Json形式返回。

package com.lyan.web_note.modules.week_day.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import com.lyan.web_note.modules.week_day.entity.WeekDay;
import com.lyan.web_note.modules.week_day.service.IWeekDayService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *  前端控制器
 * @author Lyan
 * @since 2018-09-17
 */
@RestController
@RequestMapping("/week_day/weekDay")
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
public class WeekDayController {
    @Autowired
    private IWeekDayService iWeekDayService;

    @GetMapping("/weeks")
    @ResponseBody
    public List<WeekDay> getWeeks(){
        return iWeekDayService.selectList(new EntityWrapper<>());
    }
}

运行结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/baidu_32377671/article/details/82750185