Mybatis-Generator(MBG)教程与Idea的MBG插件

简介

Mybatis Generator(MBG),下面我们统称为MBG,是一个Mybatis和iBatis的代码生成器。他可以内省数据库的表(或多个表)然后生成可以用来访问(多个)表的基础对象。这样减少了项目新建时各种配置对象,配置文件和数据库交互的麻烦。 MBG的解决了一些数据库中比较重要的操作,如CRUD(插入,查询,更新,删除)。

有关Mybatis具体生成事项,可以参考Mybatis Generator官方文档
Mybatis MBG设计用于开发环境中的交互,可以用在Ant 任务,Maven插件,持续集成环境。有关Mybatis的一些注意事项包括如下:

  • MBG 会自动合并已经存在并且和新生成的文件重名的 XML。MBG 不会覆盖您对已经生成xml所做的修改。 您可以反复的运行而不必担心失去您自定义的更改。 Mybatis Gnerator会更新上次运行生成的元素。
  • MBG 不会合并 Java 文件,如果你对一些MBG生成的文件做了修改,再次生成的时候, 您可以手动合并这些更改。 当您使用Eclipse 插件时, MBG 可以自动合并 Java 文件.

快速入门

概念

使用MBG的基本步骤
1、创建和补全Mybatis MBG的配置文件,你至少要指定以下内容

  • <jdbcConnection>素,指定如何连接数据库
  • <JavaModelGenerator>,java模型对象生成位置
  • <SqlMapGenerator>,SQL映射文件位置
  • 可选的,<javaClientGenerator>,java客户端接口和类文件位置
  • 至少一个<table>元素

2、把配置文件保存在方便的位置
3、运行MBG配置文件,可以通过Ant,Maven,Java代码等
4、修改Mybatis的一些配置,以便自己能够使用MBG生成的代码

创建项目

1、借用原来的之前的Mybatis入门教程,我们创建me.aihe.testdao包,具体结构如下。

《Mybatis-Generator(MBG)教程与Idea的MBG插件》 项目结构

2、创建MBG配置文件,如果使用Idea集成开发环境,可下载Mybatis plugin,省了不少功夫,极大的方便了我们的操作。

《Mybatis-Generator(MBG)教程与Idea的MBG插件》 新建MBG配置文件

3、修改MBG配置文件内容如下

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

    <!-- !!!! Driver Class Path !!!! -->
    <classPathEntry location="/Users/aihe/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar" />

    <!--<properties resource="classpa"-->
    <context id="context" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="false"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!-- !!!! Database Configurations !!!! -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="aihe" password="123456"/>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- !!!! Model Configurations !!!! -->
        <javaModelGenerator targetPackage="me.aihe.testdao" targetProject="/Users/aihe/IdeaProjects/MybatisCook/src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- !!!! Mapper XML Configurations !!!! -->
        <sqlMapGenerator targetPackage="me.aihe.testdao" targetProject="/Users/aihe/IdeaProjects/MybatisCook/src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- !!!! Mapper Interface Configurations !!!! -->
        <javaClientGenerator targetPackage="me.aihe.testdao" targetProject="/Users/aihe/IdeaProjects/MybatisCook/src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- !!!! Table Configurations !!!! -->
        <table tableName="Test" enableCountByExample="true" enableDeleteByExample="true" enableSelectByExample="true"
               enableUpdateByExample="true"/>
    </context>
</generatorConfiguration>

注意在<commentGenerator>里面有个suppressAllComments的属性,如果填写为true的话,所有生成的模型文件虽然会没有注释,但是Mapper.xml不会覆盖,而是追加在后面,会导致运行出错。建议设置为false

4、运行MBG
运行方式有很多种,基于Ant Task,Maven 插件,Java程序等,这里我们使用Maven Plugin。
主意:建议大家下载Idea的Maven Helper插件,方便了很多maven的操作。
配置Pom.xml文件,添加MBG插件

   <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/mybatis-generator.xml</configurationFile>
                </configuration>
            </plugin>
        </plugins>
    </build>

《Mybatis-Generator(MBG)教程与Idea的MBG插件》 运行Maven插件

5、查看结果

《Mybatis-Generator(MBG)教程与Idea的MBG插件》 生成结果
《Mybatis-Generator(MBG)教程与Idea的MBG插件》 生成结果

6、测试生成的代码
我们的数据库内容如下

《Mybatis-Generator(MBG)教程与Idea的MBG插件》 Test表内容

测试程序

  @Test
    public void test11(){
        InputStream inputStream = null;
        SqlSession sqlSession = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory mSqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = mSqlSessionFactory.openSession();

            TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
            TestExample testExample =  new TestExample();
            TestExample.Criteria criteria = testExample.createCriteria();
            criteria.andContentLike("%内容%");

            List<me.aihe.dao.Test>  testList = testMapper.selectByExample(testExample);
            System.out.println(testList);

//            Good good = goodMapper.getGoodAndCouponMap2(1);
//            System.out.println(good);

            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

运行结果如下:

《Mybatis-Generator(MBG)教程与Idea的MBG插件》 运行结果

插件

Mybaitis Generator有一些官方的插件,可以更好的定制生成的文件内容。

//缓存插件,生成的Mapper.xml文件中添加缓存配置
 <plugin type="org.mybatis.generator.plugins.CachePlugin"></plugin>

//生成的Model文件,加上toString方法
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"</plugin>
//生成的Model文件实现Serializable接口
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
//虚拟主键插件..
<plugin type="org.mybatis.generator.plugins.VirtualPrimaryKeyPlugin"></plugin>

还有一些额外的插件,可以用途比较少,在这里就先不提到了。

总结

本文主要演示了一种通过Maven 插件来使用MBG生成JavaBean,Mapper文件的案例。最后测试了生成代码的可用性。Mybatis Generator确实方便了很多我们的工作。

小提示

如果想要生成Example类,记得在Context标签上的targetRuntime为Mybatis3。

参考

    原文作者:Real_man
    原文地址: https://www.jianshu.com/p/48b50732e6fb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞