Mybatis之逆向工程的配置和实操

一、逆向工程介绍:

MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件、接口和实体类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写(多看两遍)

二、官方文档地址

http://www.mybatis.org/generator/
在这里插入图片描述
三、官方工程地址

https://github.com/mybatis/generator/releases

在这里插入图片描述
四、逆向工程实操

1、测试用的数据表

CREATE TABLE `blog`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户的唯一标识',
  `title` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '标题',
  `summary` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '摘要',
  `content` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '//内容 // 大对象,映射 MySQL 的 Long Text 类型',
  `htmlContent` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '// 将 md 转为 html // 大对象,映射 MySQL 的 Long Text 类型
',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 28 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `blog` VALUES (1, '一个爱好相关的文章', '你的爱好是什么呢?', '唱跳rap篮球', '<p>唱跳rap篮球</p>');
INSERT INTO `blog` VALUES (2, '一个性格相关的文章', '没个人的性格都不一样啊,爱好呢', '是呀,开朗,乐观积极的人生', '<p>是呀,开朗,乐观积极的人生</p>');
INSERT INTO `blog` VALUES (3, '一个关于特长的文章', '每个人都有自己的优点吧', '优点与缺点并存', '<p>优点与缺点并存</p>');
INSERT INTO `blog` VALUES (4, '一件身边的小事', '我一口吞了一个大象', '厉害厉害', '<p>厉害厉害</p>');
INSERT INTO `blog` VALUES (5, '一个神奇的事情', '你猜呢', '不告诉你', '<p>不告诉你</p>');

2、导入依赖的jar包

方式一:导入jar包:mybatis-generator-core-1.3.2.jar

方式二:在pom.xml中添加依赖:

<!--https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core-->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.7</version>
</dependency>

3、编写generatorConfig.xml配置文件

注意:位置要放在src的同级目录下(位置不明白请查看最下面的位置图)
当然也可以放在resources等其他目录下,GeneratorSqlmap.java中的文件路径要写:
File configFile = new File("./src/main/resources/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>
   <!-- targetRuntime: 指定生成的逆向工程的版本
            MyBatis3:  生成带条件的增删改查.
            MyBatis3Simple:  生成基本的增删改查.
            Context标签:如果再次生成,建议将之前生成的数据删除,避免xml向后追加内容出现的问题。-->
   <context id="DB2Tables" targetRuntime="MyBatis3">

      <commentGenerator>
         <!-- 是否去除自动生成的注释 true:是 : false:否 -->
         <property name="suppressAllComments" value="true"/>
      </commentGenerator>

      <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
      <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                  connectionURL="jdbc:mysql://localhost:3306/mybatisdb"
                  userId="root" password="123456">
      </jdbcConnection>

      <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
      <javaTypeResolver>
         <property name="forceBigDecimals" value="false"/>
      </javaTypeResolver>

      <!-- 生成实体类的位置 -->
      <javaModelGenerator targetPackage="com.online.domain" targetProject="./src">
         <!-- enableSubPackages:是否让schema作为包的后缀 -->
         <property name="enableSubPackages" value="true"/>
         <!-- 从数据库返回的值被清理前后的空格 -->
         <property name="trimStrings" value="true"/>
      </javaModelGenerator>

      <!-- mapper映射文件生成的位置 -->
      <sqlMapGenerator targetPackage="com.online.mapper" targetProject="./src">
         <property name="enableSubPackages" value="true"/>
      </sqlMapGenerator>

      <!-- mapper接口生成的位置 -->
      <javaClientGenerator type="XMLMAPPER" targetPackage="com.online.dao" targetProject="./src">
         <property name="enableSubPackages" value="true"/>
      </javaClientGenerator>

      <!-- 指定数据库表     数据库表名:tableName   对应的实体类名:domainObjectName -->
      <table tableName="blog" domainObjectName="Blog"></table>

   </context>
</generatorConfiguration>

4、运行逆向工程,使之生成我们需要的代码

package com.online.util;

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 GeneratorSqlmap {
    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 {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5、添加配置文件SqlMapConfig.xml

为了测试Mybatis逆向生成的代码使用的,注意使用的时候要改为自己的数据库和密码等。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 引入映射配置文件 -->
    <mappers>
        <package name="com.online.dao"/>
    </mappers>
</configuration>

6、用于测试的代码

输出对应的数据说明配置成功了。

package com.online.util;

import com.online.dao.BlogMapper;
import com.online.domain.Blog;
import com.online.domain.BlogExample;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class GeneratorTest {
    public SqlSessionFactory getSqlSessionFactory() throws Exception {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

    //根据id查询
    @Test
    public void testMBG01() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog blog = mapper.selectByPrimaryKey(1);
            System.out.println(blog.getTitle());
        } finally {
            session.close();
        }
    }

    //没有条件的情况,查询全部信息
    @Test
    public void testMBG02() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            List<Blog> emps = mapper.selectByExample(null);
            for (Blog blog : emps) {
                System.out.println(blog.getTitle());
            }
        } finally {
            session.close();
        }
    }

    //按照条件查询
    @Test
    public void testMBG03() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);

            //查询字段Summary包含爱好关键字的Blog对象
            BlogExample example = new BlogExample();

            BlogExample.Criteria criteria = example.createCriteria();
            criteria.andSummaryLike("%爱好%");

            List<Blog> emps = mapper.selectByExample(example);
            for (Blog blog : emps) {
                System.out.println(blog.getSummary());
            }
        } finally {
            session.close();
        }
    }
}

7、各个文件的放置位置

在这里插入图片描述
注意:对于数据库名称,密码,包结构等要根据自己的实际情况进行配置,好了,结束。
结束。

原文地址:https://www.cnblogs.com/mxxbc/p/14055695.html