MyBatis三剑客之MyBatis_Generator的配置与使用

MyBatis三剑客

MyBatis三剑客在MyBatis组件里非常实用,分别是MyBaits-generatorMyBatis-pluginsMyBatis分页插件-PageHelper。在“三剑客”中,MyBatis-generator的使用频率最高<小声逼逼,自我感觉的....>。下面分别对三剑客一一介绍。

MyBatis-Generator的基本使用

项目依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.imooc</groupId>
    <artifactId>mybatis-generator-for-imooc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>


    <dependencies>

        <!-- 引入log4j日志依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
            <version>1.3.8.RELEASE</version>
        </dependency>

        <!-- 阿里开源数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--pagehelper-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- mybatis 逆向生成工具  -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
    </dependencies>

</project>
MyMapper.java
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.imooc.my.mapper;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * 继承自己的MyMapper,特别注意,该接口不能别扫描到,否则会报错
 */
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
GeneratorDisplay.java
package com.imooc.mybatis.utils;

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.File;
import java.util.ArrayList;
import java.util.List;


public class GeneratorDisplay {

	public void generator() throws Exception {

		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		//指定 逆向工程配置文件
		File configFile = new File("generatorConfig.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);

	} 
	
	public static void main(String[] args) throws Exception {
		try {
			GeneratorDisplay generatorSqlmap = new GeneratorDisplay();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

重头戏来了,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>
    <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- 通用mapper所在目录 -->
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.imooc.my.mapper.MyMapper"/>
        </plugin>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/foodie-shop-dev?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true&amp;useSSL=false"
                        userId="root"
                        password="root123456">
        </jdbcConnection>

        <!-- 对应生成的pojo所在包 -->
        <javaModelGenerator targetPackage="com.imooc.pojo" targetProject="src/main/java"/>

				<!-- 对应生成的mapper所在目录 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

		<!-- 配置mapper对应的java映射 -->
        <javaClientGenerator targetPackage="com.imooc.mapper" targetProject="src/main/java" type="XMLMAPPER"/>

        <!-- 数据库表 -->
		<table tableName="carousel"></table>
		<table tableName="category"></table>
		<table tableName="items"></table>
		<table tableName="items_comments"></table>
		<table tableName="items_img"></table>
		<table tableName="items_param"></table>
		<table tableName="items_spec"></table>
		<table tableName="order_items"></table>
		<table tableName="order_status"></table>
		<table tableName="orders"></table>
		<table tableName="stu"></table>
		<table tableName="user_address"></table>
		<table tableName="users"></table>

    </context>
</generatorConfiguration>

需要注意的事项

1.通用mapper所在目录配置<就是指向刚才MyMapper.java所在的位置>

2.jdbcConnection中driverClassconnectionURLuserIdpassword的配置

3.配置pojo所在的包,ps:记得创建该目录下的package src/main/java/com/imooc/pojo

4.配置mapper所在的包,ps:记得创建该目录下的package src/main/resources/mapper

5.配置mapper对应的java映射的包,ps:记得创建该目录下的package src/main/java/com/imooc/mapper

6.配置映射数据库表相关信息

<!-- 数据库表 -->
		<table tableName="carousel"></table>
		<table tableName="category"></table>
		<table tableName="items"></table>
		<table tableName="items_comments"></table>
		<table tableName="items_img"></table>
		<table tableName="items_param"></table>
		<table tableName="items_spec"></table>
		<table tableName="order_items"></table>
		<table tableName="order_status"></table>
		<table tableName="orders"></table>
		<table tableName="stu"></table>
		<table tableName="user_address"></table>
		<table tableName="users"></table>

7.log4j.properties

log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

整体目录结构如下图

MyBatis三剑客之MyBatis_Generator的配置与使用

8.运行GeneratorDisplay.java即可生成相关的pojo、mapper和xml映射文件

MyBatis三剑客之MyBatis_Generator的配置与使用
  1. 将生成的pojo、MyMapper、mapper.java和mapper.xml粘贴到开发工程中,注意与generator项目中路径一致
##### 开发项目中之Application.yml中配置
MyBatis三剑客之MyBatis_Generator的配置与使用

最后的最后,记得@MapperScan

MyBatis三剑客之MyBatis_Generator的配置与使用

项目gitee地址:https://gitee.com/shine_rainbow/mybatis-generator-for-imooc.git

?