亲宝软件园·资讯

展开

MybatisPlus生成映射文件

易佰菜鸟 人气:0

如何自动生成映射文件

一、pom.xml

pom.xml添加以下依赖:

		<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
		<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
        <!-- 高版本mybatis plus将这个包摘出来了,所以需要添加此依赖,低版本不需要 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>

二、MybatisPlusUtil工具类

package com.yss.datamiddle.common;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.querys.DB2Query;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @description: 数据库生成JAVA类
 * @create: 2020-07-20 14:00:00
 * @update: 2020-07-20 14:00:00
 */
public class MybatisPlusUtils {
    /**
     * mysql自动代码生成类
     *
     * @param includeTables
     * @param excludeTables
     */
    public static void generateMysql(String[] includeTables, String[] excludeTables, Boolean db1) {
        AutoGenerator autoGenerator = new AutoGenerator();
        /**
         * 数据库配置
         */
        buildMysqlDb(autoGenerator);
        StrategyConfig strategyConfig = new StrategyConfig();
        // 驼峰命名
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setInclude(includeTables);
        strategyConfig.setExclude(excludeTables);
        strategyConfig.setTablePrefix("");
        autoGenerator.setStrategy(strategyConfig);
        /**
         * 全局配置
         */
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setAuthor("Han LiDong");
        globalConfig.setDateType(DateType.ONLY_DATE);
        globalConfig.setActiveRecord(true);
        globalConfig.setIdType(IdType.INPUT);
        globalConfig.setOutputDir("C:/D/ORM");  //文件生成路径
        globalConfig.setMapperName("%sMapper");
        globalConfig.setServiceName("%sService");
        globalConfig.setServiceImplName("%sServiceImpl");
        globalConfig.setXmlName("%sMapper");
        globalConfig.setSwagger2(true);
        globalConfig.setFileOverride(true);
        globalConfig.setBaseColumnList(false);
        globalConfig.setBaseResultMap(false);
        globalConfig.setEnableCache(false);
        autoGenerator.setGlobalConfig(globalConfig);
        /**
         * 包名配置
         */
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("");
        packageConfig.setEntity("com.yss.datamiddle.entity");
        packageConfig.setMapper("com.yss.datamiddle.dao");
        packageConfig.setXml("mapper");
        packageConfig.setService("com.yss.datamiddle.service");
        packageConfig.setServiceImpl("com.yss.datamiddle.impl");
        packageConfig.setController("com.yss.datamiddle.controller");
        autoGenerator.setPackageInfo(packageConfig);
        // 采用默认模板,自定义模板参考@see com.baomidou.mybatisplus.generator.config.TemplateConfig
//        TemplateConfig templateConfig = new TemplateConfig();
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        autoGenerator.execute();
    }
    /**
     * oracle自动代码生成类
     * @param includeTables
     * @param excludeTables
     */
    public static void generateOracle(String[] includeTables, String[] excludeTables, Boolean db1) {
        AutoGenerator autoGenerator = new AutoGenerator();
        buildOracleDb(autoGenerator);
        StrategyConfig strategyConfig = new StrategyConfig();
        // 驼峰命名
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setInclude(includeTables);
        strategyConfig.setExclude(excludeTables);
        strategyConfig.setTablePrefix("");
        autoGenerator.setStrategy(strategyConfig);
        /**
         * 全局配置
         */
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setAuthor("Han LiDong");
        globalConfig.setDateType(DateType.ONLY_DATE);
        globalConfig.setActiveRecord(true);
        globalConfig.setIdType(IdType.AUTO);    //这里用oracle的序列和触发器实现主键自增
        globalConfig.setOutputDir("C:/ORM");  //文件生成路径
        globalConfig.setMapperName("%sMapper");
        globalConfig.setServiceName("%sService");
        globalConfig.setServiceImplName("%sServiceImpl");
        globalConfig.setXmlName("%sMapper");
        globalConfig.setSwagger2(true);
        globalConfig.setFileOverride(true);
        globalConfig.setBaseColumnList(false);
        globalConfig.setBaseResultMap(false);
        globalConfig.setEnableCache(false);
        autoGenerator.setGlobalConfig(globalConfig);
        /**
         * 包名配置
         */
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("");
        packageConfig.setEntity("com.yss.datamiddle.entity");
        packageConfig.setMapper("com.yss.datamiddle.dao");
        packageConfig.setXml("mapper");
        packageConfig.setService("com.yss.datamiddle.service");
        packageConfig.setServiceImpl("com.yss.datamiddle.impl");
        packageConfig.setController("com.yss.datamiddle.controller");
        autoGenerator.setPackageInfo(packageConfig);
        // 采用默认模板,自定义模板参考@see com.baomidou.mybatisplus.generator.config.TemplateConfig
//        TemplateConfig templateConfig = new TemplateConfig();
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        autoGenerator.execute();
    }
    private static void buildOracleDb(AutoGenerator autoGenerator) {
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbQuery(new MyDbQuery());   //自定义dbquery不然querydb.dbtype找不到
        dataSourceConfig.setDbType(DbType.ORACLE);
        dataSourceConfig.setDriverName("oracle.jdbc.driver.OracleDriver");
        dataSourceConfig.setUsername("xxxxx");
        dataSourceConfig.setPassword("xxxxx");
        dataSourceConfig.setUrl("jdbc:oracle:thin:@192.168.xxx.xxx/orcl");
        //dataSourceConfig.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false");
        autoGenerator.setDataSource(dataSourceConfig);
    }
    private static void buildMysqlDb(AutoGenerator autoGenerator) {
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        dataSourceConfig.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false");
        autoGenerator.setDataSource(dataSourceConfig);
    }
    public static void main(String[] args) {
        //String[] includeTables = {"hr_kpi_dept_person","sys_user"};
        String[] includeTables = {"ETL_MIDDLE_STATE"};
        //generateMysql(includeTables,null,false);  //mysql映射文件生成
        generateOracle(includeTables,null,false);      //oracle映射文件生成
    }
}

右键 Run 运行之后就会生成一堆映射文件,将之copy到自己的项目中就可以了

生成之后去自己配置的本地目录下查看生成的文件就行了

注意: 生成的dao层文件需要自己添加@Mapper注解

自动映射autoMappingBehavior与mapUnderscoreToCamelCase

autoMappingBehavior

在Mybatis的配置文件中添加settings属性的autoMappingBehavior

<settings> 
<setting name="autoMappingBehavior" value="NONE"/> 
</settings>

autoMappingBehavior有三个属性(默认是PARTIAL)

自动映射的时候sql语句的结果集字段是不区分大小写的,所以映射的pojo成员变量也不需要区分大小写,都可以映射到。

mapUnderscoreToCamelCase

如果数据库符合命名规范,即每个单词之间用下划线连接,pojo类符合驼峰式命名,就可以设置mapUnderscoreToCamelCase为true,这样就可以自动映射。

不用再给select语句的结果集字段起别名来对应pojo类的成员

一个配置完整的 settings 元素的示例如下:

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论