Development tools: Mybatis.Plus. plug-in reverse engineering in three ways

Source code of this article: GitHub·click here || GitEE·click here

1. Introduction to reverse engineering

In Java development, the most commonly used framework for the persistence layer is mybatis. This framework requires sql statements. Mybatis officially provides reverse engineering to automatically generate the basic code required for execution of the data table, such as mapper interface, sql mapping file, pojo Entity classes, etc., to avoid the complicated process of basic code maintenance.

In actual use, the commonly used reverse engineering methods are as above, mybatis framework, mybatis-plus framework, and plug-in methods.

Two, Mybatis way

1. Basic description

Based on xml configuration, generate mybatis basic code, including mapper interface, Mapper mapping file, pojo entity class, PojoExample condition tool class.

2. Configuration file

Note that the targetProject here needs to configure a custom path location.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
		PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
		"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
	<context id="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true"/>
			<property name="suppressDate" value="false"/>
			<!-- 是否添加数据表中字段的注释 true:是 : false:否 -->
			<property name="addRemarkComments" value="true"/>
		</commentGenerator>

		<!--数据库的信息:驱动类、连接地址、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/defined-log?tinyInt1isBit=false"
			userId="root" password="123456">
		</jdbcConnection>

		<!--
			默认false,把JDBC decimal 和 numeric 类型解析为 Integer
		    设置true时把JDBC decimal 和 numeric 类型解析为BigDecimal
		-->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- 生成POJO类的位置 -->
		<javaModelGenerator targetPackage="com.generator.mybatis.pojo"
			targetProject="存放路径">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!-- 生成Mapper映射文件的位置 -->
		<sqlMapGenerator targetPackage="com.generator.mybatis.xml"
			targetProject="存放路径">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<!-- 生成Mapper接口的位置 -->
		<javaClientGenerator type="XMLMAPPER" targetPackage="com.generator.mybatis.mapper"
			targetProject="存放路径">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>

		<!-- 指定数据库表 -->
		<table schema="" tableName="dt_defined_log" domainObjectName="DefinedLog"/>

	</context>
</generatorConfiguration>

3. Startup

Read the configuration file and execute it.

public class GeneratorMybatis {
    
    

    public void generator() throws Exception {
    
    
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = Resources.getResourceAsFile("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,callback, warnings);
        myBatisGenerator.generate(null);
    }

    public static void main(String[] args) throws Exception {
    
    
        try {
    
    
            GeneratorMybatis generatorMybatis = new GeneratorMybatis();
            generatorMybatis.generator();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

Three, MybatisPlus way

1. Basic description

Compared with Mybatis, MybatisPlus provides more enhanced capabilities. Single-table operations are basically encapsulated. Therefore, the generated mapper mapping file is much simpler, and you need to pay attention to the ServiceImpl key class and the BaseMapper interface.

2. Core startup class

The configuration here can be based on many custom strategies. The code generated by the case has been transferred to the warehouse and can be downloaded and viewed by yourself.

public class GeneratorMybatisPlus {
    
    

    public static void main(String[] args) {
    
    
        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();
        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        //生成文件的输出目录
        String path="存放路径";
        globalConfig.setOutputDir(path);
        // Author设置作者
        globalConfig.setAuthor("mybatis-plus");
        // 文件覆盖
        globalConfig.setFileOverride(true);
        // 生成后打开文件
        globalConfig.setOpen(false);
        // 自定义文件名风格,%s自动填充表实体属性
        globalConfig.setMapperName("%sMapper");
        globalConfig.setXmlName("%sMapper");
        globalConfig.setServiceName("%sDao");
        globalConfig.setServiceImplName("%sDaoImpl");
        globalConfig.setEntityName("%s");
        globalConfig.setControllerName("%sController");
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/defined-log?tinyInt1isBit=false");
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456");
        autoGenerator.setDataSource(dataSourceConfig);

        // 包名配置
        PackageConfig packageConfig = new PackageConfig();
        // 父包和子包名分开处理
        packageConfig.setParent("com.generator.mybatis.plus");
        packageConfig.setController("web");
        packageConfig.setEntity("pojo");
        packageConfig.setMapper("mapper");
        packageConfig.setService("dao");
        packageConfig.setServiceImpl("dao.impl");
        autoGenerator.setPackageInfo(packageConfig);

        // 生成策略配置
        StrategyConfig strategy = new StrategyConfig();
        //设置命名格式
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 实体是否为lombok模型,默认 false
        strategy.setEntityLombokModel(true);
        //生成 @RestController 控制器
        strategy.setRestControllerStyle(true);
        // 驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        //表和前缀处理
        strategy.setInclude("dt_defined_log".split(","));
        String[] tablePre = new String[]{
    
    "dt_"};
        strategy.setTablePrefix(tablePre);
        autoGenerator.setStrategy(strategy);
        // 执行,以上相关参数可以基于动态输入获取
        autoGenerator.execute();
    }
}

This method is the most popular development method of the current mybatis framework, and the code will be much concise.

Four, plug-in tools

1. Configure the database

Choose MySQL data source here, and download the driver configuration as prompted.

2. Connection configuration

Url address, account number, password, get connection.

3. Plug-in use

The choice here is to install the EasyCode plugin.

According to the configuration, the reverse engineering file is generated. The overall idea is the same as the above two methods.

Five, source code address

GitHub·地址
https://github.com/cicadasmile/data-manage-parent
GitEE·地址
https://gitee.com/cicadasmile/data-manage-parent

Recommended reading: finishing programming system

Serial number project name GitHub address GitEE address Recommended
01 Java describes design patterns, algorithms, and data structures GitHub·click here GitEE·Click here ☆☆☆☆☆
02 Java foundation, concurrency, object-oriented, web development GitHub·click here GitEE·Click here ☆☆☆☆
03 Detailed explanation of SpringCloud microservice basic component case GitHub·click here GitEE·Click here ☆☆☆
04 SpringCloud microservice architecture actual combat comprehensive case GitHub·click here GitEE·Click here ☆☆☆☆☆
05 Getting started with SpringBoot framework basic application to advanced GitHub·click here GitEE·Click here ☆☆☆☆
06 SpringBoot framework integrates and develops common middleware GitHub·click here GitEE·Click here ☆☆☆☆☆
07 Basic case of data management, distribution, architecture design GitHub·click here GitEE·Click here ☆☆☆☆☆
08 Big data series, storage, components, computing and other frameworks GitHub·click here GitEE·Click here ☆☆☆☆☆

Guess you like

Origin blog.csdn.net/cicada_smile/article/details/109432666