逆向工具使用 (根据表生成类)

mybatis generaot

java 方式生成

  • 引入依赖
 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.31</version>
        </dependency>
    <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itfsw</groupId>
            <artifactId>mybatis-generator-plugin</artifactId>
            <version>1.3.7</version>
            <scope>test</scope>
        </dependency>
  • 创建generatorConfig.xml 文件:
<?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="store" targetRuntime="MyBatis3">
    
<!--        自定义插件,生成分页,回填主键,mapper注释-->
<!--         <plugin type="org.mybatis.generator.plugins.MapperConfigPlugin">--></plugin>
        <!--        不合并 ,否则重写属性生效-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"></plugin>
        <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"></plugin>
        <plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin">
            <!--
            开启后可以实现官方插件根据属性是否为空决定是否插入该字段功能
            !需开启allowMultiQueries=true多条sql提交操作,所以不建议使用!插件默认不开启
            -->
            <property name="allowMultiQueries" value="false" />
        </plugin>
        <!--        自定义插件,生成分页,回填主键,mapper注释-->
        <plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin">
            <!-- 通过配置startPage影响Example中的page方法开始分页的页码,默认分页从0开始 -->
            <property name="startPage" value="0" />
        </plugin>
        <!-- Mapper注解插件 -->
    <plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin">
        <!-- @Mapper 默认开启 -->
        <property name="@Mapper" value="true"/>
        <!-- @Repository 默认关闭,开启后解决IDEA工具@Autowired报错 -->
        <property name="@Repository" value="false"/>
    </plugin>
                
      <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
            <!-- 是否去除所有自动生成的文件的时间戳,默认为false -->
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<!--        &在xml中准换为&amp;需要执行库-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC&amp;autoReconnect=true&amp;maxReconnects=1&amp;initialTimeout=50000&amp;failOverReadOnly=false&amp;zeroDateTimeBehavior=convertToNull&amp;connectTimeout=50000&amp;socketTimeout=50000"
            userId="root"
            password="123456"></jdbcConnection>
    
        <!-- targetPackage:包名称(自定义)  targetProject:项目路径(自定义)   -->
        <!--定义model的包名称-->
        <javaModelGenerator targetPackage="com.knowledge.dao.entity" targetProject="src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格  -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 配置生成相应的实体Mapper.xml,对于Mapper3.X我们需要把type="XMLMAPPER" -->
        <!-- targetPackage:包名称(自定义)  targetProject:项目路径(自定义)   -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- 配置生成相应的接口类,对应与Mapper.xml中的一系列CRUD方法SQL语句 -->
        <!-- targetPackage:包名称(自定义)  targetProject:项目路径(自定义)   -->
        <javaClientGenerator targetPackage="com.knowledge.dao" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!-- %号会生成所有表, -->
        <table schema="knowledgeshare" tableName="%">
        </table>
<!--        <table schema="knowledgeshare" tableName="group_info">-->
<!--        </table>-->

    </context>
</generatorConfiguration>
  • 使用java 类方式创建生成类 CodeMybatisGenerator:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class CodeMybatisGenerator {
    public static void main(String[] args) throws FileNotFoundException {
        List<String> warnings = new ArrayList<>();
        // 当生成的代码重复时,覆盖源代码
        boolean overwrite = true;
        // 读取MBG配置文件
        InputStream is = new FileInputStream("src/test/resources/generatorConfig.xml");

        ConfigurationParser cp = new ConfigurationParser(warnings);
        DefaultShellCallback shellCallback = new DefaultShellCallback(overwrite);
        Configuration configuration = null;
        try {
            configuration = cp.parseConfiguration(is);
            is.close();
            // 创建MBG
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, shellCallback, warnings);
            // 执行生成代码
            myBatisGenerator.generate(null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        for (String warning : warnings) {
            System.out.println(warning);
        }
    }

}

  • 注意点:
    1. 使用main方式时,引入mysql-connector-java 依赖后,不需要再xml文件中手动指定mysql-connector-java jar包的路径了

使用maven 插件方式生成

  • pom 中引入如下(指定配置文件位置以及依赖的jar包):
 <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>
                        src/test/resources/generatorConfig.xml
                    </configurationFile>
                    <verbose>true</verbose>
                    <overwrite>false</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.31</version>
                    </dependency>
                    <dependency>
                        <groupId>groupId</groupId>
                        <artifactId>codegenerate</artifactId>
                        <version>1.0-SNAPSHOT</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
  • 运行generator即可
  • maven 插件所以来的jar包和项目不同,需要再build中额外添加所依赖的组件

自定义mybatis generator 介绍

  • 继承PluginAdapter类,其中validate返回true;
  • 实现增加mapper 注解,merge通过反射设置为false;
  • 基础:
    1. 增加 import:
      1. 使用 FullyQualifiedJavaType,构造方法中添加参数完成的类路径
      2. 对应的类中调用 addImportedType 方法
    2. 添加接口注释:
      1. 调用addAnnotation 方式,参数为注释的完整字符串
    3. 增加model 类元素:
      1. 构建field 对象,设置元素的名称 ,可见性 ,类型
      2. 元素的类型 需要封装,如int 类型,需要调用FullyQualifiedJavaType.getIntInstance().getPrimitiveTypeWrapper() 得到对应int 类型实例的对象,注意getIntInstance() 中int;
      3. 对应的类中添加addField();
    4. 增加对应元素的get set方法:
      1. 构建Method,设置可见性,名称,参数,方法体
      2. 参数要使用 Parameter对象,其构造函数中传入 类型包裹,名称
      3. 返回值使用 类型包裹
      4. 方法体使用字符串代码
      //添加 注释的import 
        FullyQualifiedJavaType javaType=new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper");
        interfaze.addImportedType(javaType);
        //添加注释 接口级别
        interfaze.addAnnotation("@Mapper");


        //添加元素
        Field limit = new Field();
        limit.setName("limit");
        limit.setVisibility(JavaVisibility.PRIVATE);
        limit.setType(integerWrapper);
        topLevelClass.addField(limit);
        //添加set get方法
        Method setLimit = new Method();
        setLimit.setVisibility(JavaVisibility.PUBLIC);
        setLimit.setName("setLimit");
        setLimit.addParameter(new Parameter(integerWrapper, "limit"));
        setLimit.addBodyLine("this.limit = limit;");
        topLevelClass.addMethod(setLimit);
        //get 方式
        getLimit.setReturnType(integerWrapper);

  • 实现需要改动的方法
    1. clientGenerated : java接口准备完成后调用
    2. modelExampleClassGenerated : model类的example 类准备完成后调用
    3. sqlMapSelectByExampleWithoutBLOBsElementGenerated xml 文件中SelectByExample类型准备完成后调用
    4. sqlMapInsertElementGenerated :insert 语句准备完成后调用
    5. sqlMapInsertSelectiveElementGenerated :InsertSelective语句准备完成后调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值