MyBatis 逆向工程介绍

MyBatis 逆向工程介绍

1. 概念:


逆向工程就是根据数据库中对应的表在项目工程中生成相应的MyBatis代码(XXXMapper.java/XXXMapper.xml/Moudle(XXX)),逆向工程生成的代码可以进行简单的数据库操作,能够节省不少的时间,MyBatis官方提供了相应的代码,所以在实际中运用较多。

2. 操作配置


1. 下载相应的jar包,主要有两个:

MyBatis 逆向工程介绍

  下载链接(文章结尾附有完整项目代码)://download.****.net/download/weixin_45910396/12013449

2. 项目目录:

MyBatis 逆向工程介绍


3. main方法:

导入jar之后编写核心代码:打开网址

MyBatis 逆向工程介绍


代码如下:

public static void main(String[] args)throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("src/generator.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);
    }

4. generator.xml配置文件

同样的网址,打开 XML Configuration Reference

MyBatis 逆向工程介绍


我的代码如下:

<?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">

<gen 大专栏  MyBatis 逆向工程介绍eratorConfiguration>

    <context >

        <!--数据库配置-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="root0809">
        </jdbcConnection>

        <!-- java类型解析 -->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 模型生成包名-->
        <javaModelGenerator targetPackage="com.seven.model" targetProject=".src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- mybatis的映射.xml-->
        <sqlMapGenerator targetPackage="com.seven.mapper" targetProject=".src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- mybatis 的mapper接口生成的包路径-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.seven.mapper" targetProject=".src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 配置生成表的模型-->
        <table tableName="rs" domainObjectName="Rs"/>
        <table tableName="pollutiontrend" domainObjectName="PollutionTrend"/>

    </context>
</generatorConfiguration>

至此,MyBatis逆向工程的所有配置都已经完成了,运行main方法即可得到对应的model和mapper以及mapper.xml文件。

  附上完整的项目代码,直接下载即可使用://download.****.net/download/weixin_45910396/12013612

运行MyBatis 逆向工程,发现在model文件夹下生成了XXXExample类,关于Example类的详细介绍可以参考另一篇文章《Mybatis逆向工程中生成的Example类详细介绍》