SSM框架——使用 MyBatis Generator 生成代码,包括:Model、Dao、Mapping

基于 SSM 框架开发,Mybatis 属于半自动 ORM,如果每个数据表相关的 Model、Dao、Mapping 都要自己动手去写,是不是很麻烦呢?工作量最大的就是书写Mapping的映射文件,而且手动书写很容易出错。

这里就介绍一个用于 MyBatis 的代码生成工具 MyBatis Generator,MyBatis Generator  简称(MBG)是 MyBatis 和 iBATIS 的代码生成器。
它将生成所有版本的MyBatis的代码,以及版本2.2.0之后的iBATIS版本。它将内省数据库表(或许多表),并将生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表进行交互的最初麻烦。MBG旨在对简单的CRUD(创建,检索,更新,删除)的大量数据库操作产生重大影响。您仍然需要为连接查询或存储过程手动编写 SQL 和对象。更多请参考:MyBatis Generator (MBG) 代码生成器简介

本文参考:MyBatis Generator 代码生成器 快速入门指南

本文完整示例下载:MyBatis Generator 代码生成器+MySQL驱动+配置文件

工作原理

代码生成器需要一个实现 DatabaseMetaData 接口的 JDBC 驱动程序,尤其是 getColumns 和 getPrimaryKeys 方法。

通过 DatabaseMetaData 数据库元数据信息接口,可以获取数据库中有哪些表,表中有哪些列以及列的数据类型、长度、是否允许为空、注释,主键是什么等信息,根据这些信息再根据实体类(Entity 或 POJO)的格式、MyBatis 的 Mapper.xml 格式、Dao 层类的格式等生成对应的文件。

前期准备

1、下载 MyBatis Generator 

最新版本:MyBatis Generator Release 1.3.5

有关版本的更多信息请参考:MyBatis Generator中的新功能

2、下载数据库驱动程序

连接不同的数据库,需要使用对应的驱动程序。

针对 MySQL,我们需要下载 Connector/J,MySQL Connector / J是MySQL的官方JDBC驱动程序。

最新版本:Connector/J 5.1.44

3、编写配置文件

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>
	<classPathEntry location="mysql-connector-java-5.1.30.jar" />

	<context id="DB2Tables" targetRuntime="MyBatis3">
		<!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <commentGenerator>
			<property name="suppressDate" value="true"/>
			<property name="suppressAllComments" value="true"/>
		</commentGenerator>
		<!--数据库链接URL,用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/db_test" userId="root"
			password="xxx">
		</jdbcConnection>

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

		<javaModelGenerator targetPackage="test.model"
			targetProject="./src">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<sqlMapGenerator targetPackage="test.xml"
			targetProject="./src">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<javaClientGenerator type="XMLMAPPER"
			targetPackage="test.dao" targetProject="./src">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>

		<table tableName="base_area">
			
		</table>

	</context>
</generatorConfiguration>

注意:你使用的版本号可能与我的不同。classPathEntry 标签中的“mysql-connector-java-5.1.30.jar” 要改为对应的版本。jdbcConnection 数据库连接信息需要修改为你自己的实际的信息。table 标签必须存在,一个标签只能指定一个表,多个表可以存在多个 table 标签。

tableName 可以使用通配符 % 来匹配全部的表,例如:

	<table tableName="%">
		<generatedKey column="id" sqlStatement="Mysql"/>
	</table>

更多细节请参考:MyBatis Generator XML 配置文件参考

4、关于包的存放目录

将 mybatis-generator-core-1.3.5.jar,mysql-connector-java-5.1.30.jar,generatorConfig.xml 等文件放在同一个目录下,

参考我的目录结构:

SSM框架——使用 MyBatis Generator 生成代码,包括:Model、Dao、Mapping

注意:你使用的版本号可能与我的不同。src 目录需要你自己创建。生成的文件会按配置文件中指定的包名创建目录结构。

生成代码

1、打开终端

2、切换目录到 mybatis-generator-core-1.3.5.jar,mysql-connector-java-5.1.30.jar,generatorConfig.xml 等文件所在的目录

3、执行命令

$ java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite
看到输出:

MyBatis Generator finished successfully.

就说明生成成功了。

常见错误:

你可能会遇到错误一:

Exception in thread "main" java.lang.RuntimeException: Cannot resolve classpath
entry: mysql-connector-java-5.1.30.jar
        at org.mybatis.generator.internal.util.ClassloaderUtility.getCustomClass
loader(ClassloaderUtility.java:49)
        at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.
java:245)
        at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.
java:189)
        at org.mybatis.generator.api.ShellRunner.main(ShellRunner.java:117)
Cannot resolve classpath entry: mysql-connector-java-5.1.30.jar
查看 generatorConfig.xml 文件所在的目录中是否存在名称为“mysql-connector-java-5.1.30.jar”的文件,

是不是你下载的版本和我用的不一致?改为对应的版本的文件名称就可以了。

错误二:

XML Parser Errors occurred:
XML Parser Error on line 1: 前言中不允许有内容。

在 Windows 下遇到这个问题,解决方法:采用无 BOM 格式编码

SSM框架——使用 MyBatis Generator 生成代码,包括:Model、Dao、Mapping

错误三:

The specified target project directory ./src does not exist

你需要手动创建一个目录。

代码预览

数据表结构

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `base_area`
-- ----------------------------
DROP TABLE IF EXISTS `base_area`;
CREATE TABLE `base_area` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `AREA_NAME` varchar(255) DEFAULT NULL COMMENT '地区名称',
  `AREA_CODE` varchar(255) DEFAULT NULL COMMENT '地区编码',
  `PARENT_ID` bigint(20) DEFAULT NULL COMMENT '上级地区编号',
  `PLAT_MARK` bigint(20) DEFAULT NULL COMMENT '区域标识,也就是平台标识',
  `LEVEL` tinyint(4) DEFAULT '1' COMMENT '级别',
  `STATUS` tinyint(4) DEFAULT '1' COMMENT '是否可用、是否显示',
  `EXPAND` tinyint(4) DEFAULT '0' COMMENT '是否展开子节点,非0为展开。',
  PRIMARY KEY (`ID`),
  KEY `index2` (`PLAT_MARK`)
) ENGINE=InnoDB AUTO_INCREMENT=3514 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;
生成的代码文件:

dao/BaseAreaMapper.java

package test.dao;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import test.model.BaseArea;
import test.model.BaseAreaExample;

public interface BaseAreaMapper {
    long countByExample(BaseAreaExample example);

    int deleteByExample(BaseAreaExample example);

    int deleteByPrimaryKey(Long id);

    int insert(BaseArea record);

    int insertSelective(BaseArea record);

    List<BaseArea> selectByExample(BaseAreaExample example);

    BaseArea selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") BaseArea record, @Param("example") BaseAreaExample example);

    int updateByExample(@Param("record") BaseArea record, @Param("example") BaseAreaExample example);

    int updateByPrimaryKeySelective(BaseArea record);

    int updateByPrimaryKey(BaseArea record);
}
model/BaseArea.java

package test.model;

public class BaseArea {
    private Long id;

    private String areaName;

    private String areaCode;

    private Long parentId;

    private Long platMark;

    private Byte level;

    private Byte status;

    private Byte expand;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName == null ? null : areaName.trim();
    }

    public String getAreaCode() {
        return areaCode;
    }

    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode == null ? null : areaCode.trim();
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public Long getPlatMark() {
        return platMark;
    }

    public void setPlatMark(Long platMark) {
        this.platMark = platMark;
    }

    public Byte getLevel() {
        return level;
    }

    public void setLevel(Byte level) {
        this.level = level;
    }

    public Byte getStatus() {
        return status;
    }

    public void setStatus(Byte status) {
        this.status = status;
    }

    public Byte getExpand() {
        return expand;
    }

    public void setExpand(Byte expand) {
        this.expand = expand;
    }
}
model/BaseAreaExample.java

package test.model;

import java.util.ArrayList;
import java.util.List;

public class BaseAreaExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public BaseAreaExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andIdIsNull() {
            addCriterion("ID is null");
            return (Criteria) this;
        }

        public Criteria andIdIsNotNull() {
            addCriterion("ID is not null");
            return (Criteria) this;
        }

        public Criteria andIdEqualTo(Long value) {
            addCriterion("ID =", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotEqualTo(Long value) {
            addCriterion("ID <>", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThan(Long value) {
            addCriterion("ID >", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThanOrEqualTo(Long value) {
            addCriterion("ID >=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThan(Long value) {
            addCriterion("ID <", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThanOrEqualTo(Long value) {
            addCriterion("ID <=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdIn(List<Long> values) {
            addCriterion("ID in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotIn(List<Long> values) {
            addCriterion("ID not in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdBetween(Long value1, Long value2) {
            addCriterion("ID between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotBetween(Long value1, Long value2) {
            addCriterion("ID not between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andAreaNameIsNull() {
            addCriterion("AREA_NAME is null");
            return (Criteria) this;
        }

        public Criteria andAreaNameIsNotNull() {
            addCriterion("AREA_NAME is not null");
            return (Criteria) this;
        }

        public Criteria andAreaNameEqualTo(String value) {
            addCriterion("AREA_NAME =", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameNotEqualTo(String value) {
            addCriterion("AREA_NAME <>", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameGreaterThan(String value) {
            addCriterion("AREA_NAME >", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameGreaterThanOrEqualTo(String value) {
            addCriterion("AREA_NAME >=", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameLessThan(String value) {
            addCriterion("AREA_NAME <", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameLessThanOrEqualTo(String value) {
            addCriterion("AREA_NAME <=", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameLike(String value) {
            addCriterion("AREA_NAME like", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameNotLike(String value) {
            addCriterion("AREA_NAME not like", value, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameIn(List<String> values) {
            addCriterion("AREA_NAME in", values, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameNotIn(List<String> values) {
            addCriterion("AREA_NAME not in", values, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameBetween(String value1, String value2) {
            addCriterion("AREA_NAME between", value1, value2, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaNameNotBetween(String value1, String value2) {
            addCriterion("AREA_NAME not between", value1, value2, "areaName");
            return (Criteria) this;
        }

        public Criteria andAreaCodeIsNull() {
            addCriterion("AREA_CODE is null");
            return (Criteria) this;
        }

        public Criteria andAreaCodeIsNotNull() {
            addCriterion("AREA_CODE is not null");
            return (Criteria) this;
        }

        public Criteria andAreaCodeEqualTo(String value) {
            addCriterion("AREA_CODE =", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeNotEqualTo(String value) {
            addCriterion("AREA_CODE <>", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeGreaterThan(String value) {
            addCriterion("AREA_CODE >", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeGreaterThanOrEqualTo(String value) {
            addCriterion("AREA_CODE >=", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeLessThan(String value) {
            addCriterion("AREA_CODE <", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeLessThanOrEqualTo(String value) {
            addCriterion("AREA_CODE <=", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeLike(String value) {
            addCriterion("AREA_CODE like", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeNotLike(String value) {
            addCriterion("AREA_CODE not like", value, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeIn(List<String> values) {
            addCriterion("AREA_CODE in", values, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeNotIn(List<String> values) {
            addCriterion("AREA_CODE not in", values, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeBetween(String value1, String value2) {
            addCriterion("AREA_CODE between", value1, value2, "areaCode");
            return (Criteria) this;
        }

        public Criteria andAreaCodeNotBetween(String value1, String value2) {
            addCriterion("AREA_CODE not between", value1, value2, "areaCode");
            return (Criteria) this;
        }

        public Criteria andParentIdIsNull() {
            addCriterion("PARENT_ID is null");
            return (Criteria) this;
        }

        public Criteria andParentIdIsNotNull() {
            addCriterion("PARENT_ID is not null");
            return (Criteria) this;
        }

        public Criteria andParentIdEqualTo(Long value) {
            addCriterion("PARENT_ID =", value, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdNotEqualTo(Long value) {
            addCriterion("PARENT_ID <>", value, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdGreaterThan(Long value) {
            addCriterion("PARENT_ID >", value, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdGreaterThanOrEqualTo(Long value) {
            addCriterion("PARENT_ID >=", value, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdLessThan(Long value) {
            addCriterion("PARENT_ID <", value, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdLessThanOrEqualTo(Long value) {
            addCriterion("PARENT_ID <=", value, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdIn(List<Long> values) {
            addCriterion("PARENT_ID in", values, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdNotIn(List<Long> values) {
            addCriterion("PARENT_ID not in", values, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdBetween(Long value1, Long value2) {
            addCriterion("PARENT_ID between", value1, value2, "parentId");
            return (Criteria) this;
        }

        public Criteria andParentIdNotBetween(Long value1, Long value2) {
            addCriterion("PARENT_ID not between", value1, value2, "parentId");
            return (Criteria) this;
        }

        public Criteria andPlatMarkIsNull() {
            addCriterion("PLAT_MARK is null");
            return (Criteria) this;
        }

        public Criteria andPlatMarkIsNotNull() {
            addCriterion("PLAT_MARK is not null");
            return (Criteria) this;
        }

        public Criteria andPlatMarkEqualTo(Long value) {
            addCriterion("PLAT_MARK =", value, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkNotEqualTo(Long value) {
            addCriterion("PLAT_MARK <>", value, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkGreaterThan(Long value) {
            addCriterion("PLAT_MARK >", value, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkGreaterThanOrEqualTo(Long value) {
            addCriterion("PLAT_MARK >=", value, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkLessThan(Long value) {
            addCriterion("PLAT_MARK <", value, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkLessThanOrEqualTo(Long value) {
            addCriterion("PLAT_MARK <=", value, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkIn(List<Long> values) {
            addCriterion("PLAT_MARK in", values, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkNotIn(List<Long> values) {
            addCriterion("PLAT_MARK not in", values, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkBetween(Long value1, Long value2) {
            addCriterion("PLAT_MARK between", value1, value2, "platMark");
            return (Criteria) this;
        }

        public Criteria andPlatMarkNotBetween(Long value1, Long value2) {
            addCriterion("PLAT_MARK not between", value1, value2, "platMark");
            return (Criteria) this;
        }

        public Criteria andLevelIsNull() {
            addCriterion("LEVEL is null");
            return (Criteria) this;
        }

        public Criteria andLevelIsNotNull() {
            addCriterion("LEVEL is not null");
            return (Criteria) this;
        }

        public Criteria andLevelEqualTo(Byte value) {
            addCriterion("LEVEL =", value, "level");
            return (Criteria) this;
        }

        public Criteria andLevelNotEqualTo(Byte value) {
            addCriterion("LEVEL <>", value, "level");
            return (Criteria) this;
        }

        public Criteria andLevelGreaterThan(Byte value) {
            addCriterion("LEVEL >", value, "level");
            return (Criteria) this;
        }

        public Criteria andLevelGreaterThanOrEqualTo(Byte value) {
            addCriterion("LEVEL >=", value, "level");
            return (Criteria) this;
        }

        public Criteria andLevelLessThan(Byte value) {
            addCriterion("LEVEL <", value, "level");
            return (Criteria) this;
        }

        public Criteria andLevelLessThanOrEqualTo(Byte value) {
            addCriterion("LEVEL <=", value, "level");
            return (Criteria) this;
        }

        public Criteria andLevelIn(List<Byte> values) {
            addCriterion("LEVEL in", values, "level");
            return (Criteria) this;
        }

        public Criteria andLevelNotIn(List<Byte> values) {
            addCriterion("LEVEL not in", values, "level");
            return (Criteria) this;
        }

        public Criteria andLevelBetween(Byte value1, Byte value2) {
            addCriterion("LEVEL between", value1, value2, "level");
            return (Criteria) this;
        }

        public Criteria andLevelNotBetween(Byte value1, Byte value2) {
            addCriterion("LEVEL not between", value1, value2, "level");
            return (Criteria) this;
        }

        public Criteria andStatusIsNull() {
            addCriterion("STATUS is null");
            return (Criteria) this;
        }

        public Criteria andStatusIsNotNull() {
            addCriterion("STATUS is not null");
            return (Criteria) this;
        }

        public Criteria andStatusEqualTo(Byte value) {
            addCriterion("STATUS =", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusNotEqualTo(Byte value) {
            addCriterion("STATUS <>", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusGreaterThan(Byte value) {
            addCriterion("STATUS >", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusGreaterThanOrEqualTo(Byte value) {
            addCriterion("STATUS >=", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusLessThan(Byte value) {
            addCriterion("STATUS <", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusLessThanOrEqualTo(Byte value) {
            addCriterion("STATUS <=", value, "status");
            return (Criteria) this;
        }

        public Criteria andStatusIn(List<Byte> values) {
            addCriterion("STATUS in", values, "status");
            return (Criteria) this;
        }

        public Criteria andStatusNotIn(List<Byte> values) {
            addCriterion("STATUS not in", values, "status");
            return (Criteria) this;
        }

        public Criteria andStatusBetween(Byte value1, Byte value2) {
            addCriterion("STATUS between", value1, value2, "status");
            return (Criteria) this;
        }

        public Criteria andStatusNotBetween(Byte value1, Byte value2) {
            addCriterion("STATUS not between", value1, value2, "status");
            return (Criteria) this;
        }

        public Criteria andExpandIsNull() {
            addCriterion("EXPAND is null");
            return (Criteria) this;
        }

        public Criteria andExpandIsNotNull() {
            addCriterion("EXPAND is not null");
            return (Criteria) this;
        }

        public Criteria andExpandEqualTo(Byte value) {
            addCriterion("EXPAND =", value, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandNotEqualTo(Byte value) {
            addCriterion("EXPAND <>", value, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandGreaterThan(Byte value) {
            addCriterion("EXPAND >", value, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandGreaterThanOrEqualTo(Byte value) {
            addCriterion("EXPAND >=", value, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandLessThan(Byte value) {
            addCriterion("EXPAND <", value, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandLessThanOrEqualTo(Byte value) {
            addCriterion("EXPAND <=", value, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandIn(List<Byte> values) {
            addCriterion("EXPAND in", values, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandNotIn(List<Byte> values) {
            addCriterion("EXPAND not in", values, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandBetween(Byte value1, Byte value2) {
            addCriterion("EXPAND between", value1, value2, "expand");
            return (Criteria) this;
        }

        public Criteria andExpandNotBetween(Byte value1, Byte value2) {
            addCriterion("EXPAND not between", value1, value2, "expand");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}
xml/BaseAreaMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.dao.BaseAreaMapper">
  <resultMap id="BaseResultMap" type="test.model.BaseArea">
    <id column="ID" jdbcType="BIGINT" property="id" />
    <result column="AREA_NAME" jdbcType="VARCHAR" property="areaName" />
    <result column="AREA_CODE" jdbcType="VARCHAR" property="areaCode" />
    <result column="PARENT_ID" jdbcType="BIGINT" property="parentId" />
    <result column="PLAT_MARK" jdbcType="BIGINT" property="platMark" />
    <result column="LEVEL" jdbcType="TINYINT" property="level" />
    <result column="STATUS" jdbcType="TINYINT" property="status" />
    <result column="EXPAND" jdbcType="TINYINT" property="expand" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    ID, AREA_NAME, AREA_CODE, PARENT_ID, PLAT_MARK, LEVEL, STATUS, EXPAND
  </sql>
  <select id="selectByExample" parameterType="test.model.BaseAreaExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from base_area
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from base_area
    where ID = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from base_area
    where ID = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="test.model.BaseAreaExample">
    delete from base_area
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="test.model.BaseArea">
    insert into base_area (ID, AREA_NAME, AREA_CODE, 
      PARENT_ID, PLAT_MARK, LEVEL, 
      STATUS, EXPAND)
    values (#{id,jdbcType=BIGINT}, #{areaName,jdbcType=VARCHAR}, #{areaCode,jdbcType=VARCHAR}, 
      #{parentId,jdbcType=BIGINT}, #{platMark,jdbcType=BIGINT}, #{level,jdbcType=TINYINT}, 
      #{status,jdbcType=TINYINT}, #{expand,jdbcType=TINYINT})
  </insert>
  <insert id="insertSelective" parameterType="test.model.BaseArea">
    insert into base_area
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        ID,
      </if>
      <if test="areaName != null">
        AREA_NAME,
      </if>
      <if test="areaCode != null">
        AREA_CODE,
      </if>
      <if test="parentId != null">
        PARENT_ID,
      </if>
      <if test="platMark != null">
        PLAT_MARK,
      </if>
      <if test="level != null">
        LEVEL,
      </if>
      <if test="status != null">
        STATUS,
      </if>
      <if test="expand != null">
        EXPAND,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="areaName != null">
        #{areaName,jdbcType=VARCHAR},
      </if>
      <if test="areaCode != null">
        #{areaCode,jdbcType=VARCHAR},
      </if>
      <if test="parentId != null">
        #{parentId,jdbcType=BIGINT},
      </if>
      <if test="platMark != null">
        #{platMark,jdbcType=BIGINT},
      </if>
      <if test="level != null">
        #{level,jdbcType=TINYINT},
      </if>
      <if test="status != null">
        #{status,jdbcType=TINYINT},
      </if>
      <if test="expand != null">
        #{expand,jdbcType=TINYINT},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="test.model.BaseAreaExample" resultType="java.lang.Long">
    select count(*) from base_area
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update base_area
    <set>
      <if test="record.id != null">
        ID = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.areaName != null">
        AREA_NAME = #{record.areaName,jdbcType=VARCHAR},
      </if>
      <if test="record.areaCode != null">
        AREA_CODE = #{record.areaCode,jdbcType=VARCHAR},
      </if>
      <if test="record.parentId != null">
        PARENT_ID = #{record.parentId,jdbcType=BIGINT},
      </if>
      <if test="record.platMark != null">
        PLAT_MARK = #{record.platMark,jdbcType=BIGINT},
      </if>
      <if test="record.level != null">
        LEVEL = #{record.level,jdbcType=TINYINT},
      </if>
      <if test="record.status != null">
        STATUS = #{record.status,jdbcType=TINYINT},
      </if>
      <if test="record.expand != null">
        EXPAND = #{record.expand,jdbcType=TINYINT},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update base_area
    set ID = #{record.id,jdbcType=BIGINT},
      AREA_NAME = #{record.areaName,jdbcType=VARCHAR},
      AREA_CODE = #{record.areaCode,jdbcType=VARCHAR},
      PARENT_ID = #{record.parentId,jdbcType=BIGINT},
      PLAT_MARK = #{record.platMark,jdbcType=BIGINT},
      LEVEL = #{record.level,jdbcType=TINYINT},
      STATUS = #{record.status,jdbcType=TINYINT},
      EXPAND = #{record.expand,jdbcType=TINYINT}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="test.model.BaseArea">
    update base_area
    <set>
      <if test="areaName != null">
        AREA_NAME = #{areaName,jdbcType=VARCHAR},
      </if>
      <if test="areaCode != null">
        AREA_CODE = #{areaCode,jdbcType=VARCHAR},
      </if>
      <if test="parentId != null">
        PARENT_ID = #{parentId,jdbcType=BIGINT},
      </if>
      <if test="platMark != null">
        PLAT_MARK = #{platMark,jdbcType=BIGINT},
      </if>
      <if test="level != null">
        LEVEL = #{level,jdbcType=TINYINT},
      </if>
      <if test="status != null">
        STATUS = #{status,jdbcType=TINYINT},
      </if>
      <if test="expand != null">
        EXPAND = #{expand,jdbcType=TINYINT},
      </if>
    </set>
    where ID = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="test.model.BaseArea">
    update base_area
    set AREA_NAME = #{areaName,jdbcType=VARCHAR},
      AREA_CODE = #{areaCode,jdbcType=VARCHAR},
      PARENT_ID = #{parentId,jdbcType=BIGINT},
      PLAT_MARK = #{platMark,jdbcType=BIGINT},
      LEVEL = #{level,jdbcType=TINYINT},
      STATUS = #{status,jdbcType=TINYINT},
      EXPAND = #{expand,jdbcType=TINYINT}
    where ID = #{id,jdbcType=BIGINT}
  </update>
</mapper>

使用总结

1、配置文件中的标签出现的顺序是有要求的。

标签顺序一变,你可能就会看到:

XML Parser Errors occurred:

XML Parser Error on line 47: 元素类型为 "context" 的内容必须匹配 "(property*,plugin*,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeResolver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+)"。
2、配置文件中配置的输出目录是要自己创建的,否则会看到类似下面的错误提示:

The specified target project directory ./MBGTestProject/src does not exist
3、针对数据库的驱动程序包要配置正确,本例中是针对 MySQL 数据库的。 

4、table 标签必须存在,一个标签只能指定一个表,多个表可以存在多个 table 标签。

提示:tableName 可以使用通配符 % 来匹配全部的表,例如:

	<table tableName="%">
		<generatedKey column="id" sqlStatement="Mysql"/>
	</table>

5、数据表及字段都加注释了,但生成的文件中没有注释,这个还需要自己写注释相关的实现类来解决,后续补充这部分内容。

6、生成的文件怎么用呢?后续补充这部分内容。

相关阅读:

MyBatis Generator (MBG) 代码生成器简介

MyBatis Generator 代码生成器 快速入门指南

MyBatis Generator XML 配置文件参考

运行 MyBatis Generator 后的任务

运行MyBatis Generator

MyBatis Generator中的新功能


上一篇:中基协:推动基金电子合同业务是大势所趋


下一篇:云上是时候丢掉Hadoop混合部署概念了