zoukankan      html  css  js  c++  java
  • MyBatis逆向工程

    1、mybatis逆向工程概述

    mybatis是目前很流行的持久层框架,很多企业都在采用。但是其复杂繁琐的配置,重复性的实体类创建等等,消耗了程序员大量的精力,同时有些地方如果一个细小的疏忽,可能导致最终功能运行失败。例如:在几十个字段的表中,某一列的列名配置疏忽。

    基于此,mybatis推出了一套jar包,可以依据我们设计好的数据库表,自动生成pojo、mapper以及mapper.xml。有了逆向工程,便大大缩减了我们的开发时间。本章节将介绍借助idea的方式实现mybatis的逆向工程。

    1.1 idea中mybatis逆向工程的使用

    在idea中创建一个空的Javase项目,为该项目创建新的maven模块mybatis_generator,添加如下坐标

        <dependencies>
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>1.3.7</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.7</version>
                    <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                </plugin>
            </plugins>
        </build>

    1.2 编写配置文件generatorConfig

    <?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>
        <!-- classPathEntry:数据库的 JDBC驱动的jar 包地址 -->
        <classPathEntry
                location="F:\mysql-connector-java-5.1.32.jar" />
        <context id="default" targetRuntime="MyBatis3">
    
            <!-- 配置生成pojo的序列化的插件,mybatis支持很多插件,这些插件都在 org.mybatis.generator.plugins包下  -->
            <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
    
            <commentGenerator>
                <!-- 是否去除自动生成的注释 true:是 : false:否 -->
                <property name="suppressAllComments" value="false" />
            </commentGenerator>
            <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
    
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://127.0.0.1:3306/数据库名称" userId="root"
                            password="root">
            </jdbcConnection>
    
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
    
            <!-- targetProject:生成 POJO 类的位置,如果写相对位置生成在该工程的相对位置,如果写绝对位置则会在 -->
            <javaModelGenerator targetPackage="org.mybatis.pojo" targetProject="src/main/java">
                <!-- 是否对model添加 构造函数 -->
                <property name="constructorBased" value="true"/>
                <!-- enableSubPackages:是否让schema 作为包的后缀,是否允许子包,即targetPackage.schemaName.tableName -->
                <property name="enableSubPackages" value="false"/>
                <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
                <property name="immutable" value="false"/>
                <!-- 是否对类CHAR类型的列的数据进行trim操作,从数据库返回的值被清理前后的空格 -->
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!-- 生成 XML文件 -->
            <sqlMapGenerator targetPackage="org.mybatis.mapper"      targetProject="./src/main/resources">
                <property name="enableSubPackages" value="false" />
            </sqlMapGenerator>
            <!--生成接口-->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="org.mybatis.mapper"  targetProject="./src/main/java">
                <property name="enableSubPackages" value="false" />
            </javaClientGenerator>
    
    
            <!-- 指定数据库表 -->
            <table  tableName="co_export" domainObjectName="Export" mapperName="ExportDao"
                    enableCountByExample="false" enableDeleteByExample="false"
                    enableSelectByExample="false" enableUpdateByExample="false"/>
    </context>
    </generatorConfiguration>

    1.3 执行插件

    配置完成后,按照下图双击执行即可。

     也可以参考阅读:https://www.cnblogs.com/ysocean/p/7360409.html

    拓展(很重要):逆向工程可以在Dao层生成selectByExample()等类似于xxxByExample格式的方法(Factory和FactoryExample是mybatis逆向生成的类)举例

    //创建Example对象
    FactoryExample example = new FactoryExample();
    
    //对此对象提供了多种条件查询的方法
    FactoryExample.Criteria criteria = example.createCriteria();
    //设置条件 criteria.andFactoryNameLike("%厂%");//举例 List<Factory> list = factoryDao.selectByExample(example);

    Eclipse通过main方法进行生成

    package com.aoker;
    
    import java.io.File;
    import java.util.ArrayList;
    
    /*以来的坐标
        <dependencies>
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>1.3.7</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
        </dependencies>
    
     */
    
    /*jdbc.properties
    jdbc.path=D:\ruanjian\apache-maven-3.5.4-bin\repository\mysql\mysql-connector-java\5.1.6
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/saas-export-ee88
    jdbc.username=root
    jdbc.password=root
    
     */
    
    
    /* mybatis-generator-config.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>
        <!--导入属性配置-->
        <properties resource="jdbc.properties"></properties>
        <!--指定特定数据库的jdbc驱动jar包的位置-->
        <classPathEntry location="${jdbc.path}"/>
    
        <context id="context" targetRuntime="MyBatis3">
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <commentGenerator>
                <property name="suppressAllComments" value="false"/>
                <property name="suppressDate" value="true"/>
            </commentGenerator>
    
            <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
            <jdbcConnection driverClass="${jdbc.driver}"
                            connectionURL="${jdbc.url}"
                            userId="${jdbc.username}"
                            password="${jdbc.password}"/>
            <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
                NUMERIC 类型解析为java.math.BigDecimal -->
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
    
            <!--指定包名生成实体类 以及生成的地址 (可以自定义地址,如果路径不存在会自动创建) -->
            <javaModelGenerator targetPackage="com.itheima.domain.cargo" targetProject="I:ee88mybatis_demomybatis_generatorsrcmainjava">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
                <!-- 从数据库返回的值被清理前后的空格 -->
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的mapper文件 -->
            <sqlMapGenerator targetPackage="com.itheima.dao.cargo" targetProject="I:ee88mybatis_demomybatis_generatorsrcmain
    esources">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
            </sqlMapGenerator>
    
            <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                    type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                    type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                    type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
            -->
            <javaClientGenerator targetPackage="com.itheima.dao.cargo"
                                 targetProject="I:ee88mybatis_demomybatis_generatorsrcmainjava" type="XMLMAPPER">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
            </javaClientGenerator>
    
    
            <!-- 指定数据库表
    
            <table schema="saas-export" tableName="co_export" domainObjectName="Export" mapperName="ExportDao"
                   enableCountByExample="false" enableDeleteByExample="false"
                   enableSelectByExample="false" enableUpdateByExample="false"/>
    
            <table schema="saas-export" tableName="co_export_product" domainObjectName="ExportProduct" mapperName="ExportProductDao"
                   enableCountByExample="false" enableDeleteByExample="false"
                   enableSelectByExample="false" enableUpdateByExample="false"/>
    
    
            <table schema="saas-export" tableName="co_ext_eproduct" domainObjectName="ExtEproduct" mapperName="ExtEproductDao"
                   enableCountByExample="false" enableDeleteByExample="false"
                   enableSelectByExample="false" enableUpdateByExample="false"/>-->
    <!--enableCountByExample 开启统计查询带条件-->
    <!--enableDeleteByExample 开启删除带条件-->
    <!--enableSelectByExample 开启查询带条件-->
    <!--enableUpdateByExample 开启更新带条件-->
            <table schema="saas-export-ee88" tableName="co_factory" domainObjectName="Factory" mapperName="FactoryDao"
                   enableCountByExample="false" enableDeleteByExample="false"
                   enableSelectByExample="true" enableUpdateByExample="false"/>
        </context>
    </generatorConfiguration>
    
     */
    
    
    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;
    
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     *
     */
    public class GeneratorSqlMap {
    
        public void generator() throws Exception {
    
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            //指定 逆向工程配置文件
            InputStream in = GeneratorSqlMapTest.class.getClassLoader().getResourceAsStream("mybatis-generator-config.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(in);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                    callback, warnings);
            myBatisGenerator.generate(null);
            in.close();
    
        }
    
        public static void main(String[] args) throws Exception {
            try {
                GeneratorSqlMapTest generatorSqlmap = new GeneratorSqlMapTest();
                generatorSqlmap.generator();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
  • 相关阅读:
    【java】i++与++i、i--运算
    配置ssh框架启动tomcat服务器报异常Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    jsp页面第一句话报这个错Syntax error, insert "}" to complete
    oracle忘记密码用户名被锁定_解决方案
    关于c#的单例模式,static 变量,下面一篇很不错
    Entity Framework 冲突检测,这一篇我看了比较明了
    关于lambda表达式与使用局部变量的作用域问题,下面这篇不错
    C# SelectMany 的使用
    UML类图 入门 (转载)
    VS code key shortcuts for windows
  • 原文地址:https://www.cnblogs.com/kitor/p/11090585.html
Copyright © 2011-2022 走看看