浅谈MyBatisGenerator的使用

1.概述

日常中使用MyBatis最为麻烦的就是编写Mapper文件了, 如果数据库增加一张表, 这时通常会复制一个Mapper, 然后改一下namespace, 然后再改resultMap, 改resultType等等, 也忒麻烦了.

有需求就有解决方法, MyBatis Generator横空出世, 那么它有什么绝招呢?

先来看一下官网的介绍

MyBatis Generator (MBG) is a code generator for MyBatis MyBatis and iBATIS. It will generate code for all versions of MyBatis, and versions of iBATIS after version 2.2.0. It will introspect a database table (or many tables) and will generate artifacts that can be used to access the table(s). This lessens the initial nuisance of setting up objects and configuration files to interact with database tables. MBG seeks to make a major impact on the large percentage of database operations that are simple CRUD (Create, Retrieve, Update, Delete). You will still need to hand code SQL and objects for join queries, or stored procedures.

简单说, MBG是一个代码生成器, 自动生成简单的CRUD代码和SQL, 但是你仍然可以手动编写SQL和对象代码.

咦, 突然感觉幸福来的太突然了. 下面来看一下如何使用这个利器吧.

2.依赖

  • 需要jdk1.6或更高版本
  • 需要JDBCdriver实现DatabaseMeteData接口, 尤其是getColumns和getPromaryKeys方法.

3.Maven插件配置

通常我们使用Maven进行使用, 当然也可以使用命令行或者Java代码进行调用等. 可以参考Running MyBatis Generator.

在项目中加入MyBatis Generator插件即可.

<plugins>
    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.7</version>
    </plugin>
</plugins>

只是加入了插件, 那么如何来配置插件的属性呢?

在插件中指定配置文件的位置

<plugins>
    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.7</version>
        <configuration>
            <configurationFile>src/main/resources/MyBatisGenerator.xml</configurationFile>
        </configuration>
    </plugin>
</plugins>

这时, 所有的配置只需在MyBatisGenerator.xml中配置即可.

4.配置文件说明

下面是我个人使用的配置文件配置, 我把他们分为两个文件, 一个是MyBatisGenerator.xml, 一个是MyBatisGenerator.properties.

MyBatisGenerator.xml是一般不需要改动的, 只需要改动MyBatisGenerator.properties中的配置即可.

MyBatisGenerator.properties文件

# connector-j jar包位置
mg.jar.location=C:/Users/SnailMaster/.m2/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar

# 数据库连接信息
mg.user=root
mg.password=admin
mg.jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8
mg.driverClass=com.mysql.jdbc.Driver

# 工程目录
mg.targetProject=D:/IdeaProjects/snailCode

# model文件路径
mg.package.model=me.snail.web.entity
mg.path.model=src/main/java

# xml文件路径
mg.package.xml=me.snail.web.dao
mg.path.xml=src/main/resources

# dao文件路径
mg.package.dao=me.snail.web.dao
mg.path.dao=src/main/java

# 工程目录下得classpath路径, Maven项目通常是 /src/main/java
mg.path.src=src/main/java

# 要生成实体的数据库表名
mg.tableName=employee

MyBatisGenerator.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="MyBatisGenerator.properties"/>

    <!-- 数据库连接驱动jar包 -->
    <classPathEntry location="${mg.jar.location}" />

    <context id="MySQLTables" targetRuntime="MyBatis3">

        <!-- 生成的Java文件的编码 -->
        <!--<property name="javaFileEncoding" value="UTF-8"/>-->

        <commentGenerator>
            <property name="suppressAllComments" value="true" />
            <property name="addRemarkComments" value="true" />
        </commentGenerator>

        <!-- 数据库连接信息 -->
        <jdbcConnection driverClass="${mg.driverClass}"
                        connectionURL="${mg.jdbcUrl}"
                        userId="${mg.user}"
                        password="${mg.password}">
        </jdbcConnection>

        <!-- java类型处理器 -->
        <javaTypeResolver>
            <!--
                true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型
                false:默认,
                    scale>0;length>18:使用BigDecimal;
                    scale=0;length[10,18]:使用Long;
                    scale=0;length[5,9]:使用Integer;
                    scale=0;length<5:使用Short;
            -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- java模型创建器,是必须要的元素 -->
        <javaModelGenerator targetPackage="${mg.package.model}"
                            targetProject="${mg.targetProject}/${mg.path.model}">
            <!--
                在targetPackage的基础上,根据数据库的schema再生成一层package,
                最终生成的类放在这个package下,默认为false
            -->
            <property name="enableSubPackages" value="true" />
            <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
            <property name="trimStrings" value="false" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="${mg.package.xml}"
                         targetProject="${mg.targetProject}/${mg.path.xml}">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="${mg.package.dao}"
                             targetProject="${mg.targetProject}/${mg.path.dao}">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName="${mg.tableName}"></table>

    </context>
</generatorConfiguration>

5.运行

配置完成之后, 直接运行插件的mybatis-generator:generate即可自动生成代码, 爽歪歪.

如果有问题的话, 在运行时可以加入 -X 参数运行, 查看错误信息.

6.总结

这里是改插件的官方文档: http://www.mybatis.org/generator/configreference/xmlconfig.html

学习一个新技术最好的方法就是看官方文档, 然后不断的写demo.

原文地址:https://www.cnblogs.com/wuqinglong/p/9843649.html