[Mybatis] The creation and testing process of Mybatis reverse engineering [with source code]

Reverse engineering of Mybatis

Forward engineering: Create Java entity classes first, and the framework is responsible for generating database tables based on entity classes. Hibernate supports forward engineering. Reverse engineering: first create the database table, and the framework is responsible for reversely generating the following resources according to the database table: Java entity class, Mapper interface, and Mapper mapping file. To put it simply, reverse engineering is to automatically
generate java code through a single table in the database.

1. Implement reverse engineering steps

The premise is that there is a table corresponding to reverse engineering in the database .

(1) Create a Maven project (module)
insert image description here
, select maven, then click next
insert image description here
to fill in Name, GroupId, and click finish
insert image description here
(2) Add related dependencies and reverse engineering plug-ins in pom.xml

<?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.jd.wds</groupId>
    <artifactId>mybatis-MBG</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>
        <!-- MySQL数据库依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <!--Junit单元测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--log4j日志管理-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    <!-- 控制 Maven 在构建过程中相关配置 -->
    <build>
        <!-- 构建过程中用到的插件 -->
        <plugins>
            <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.0</version>
                <!-- 插件的依赖 -->
                <dependencies>
                    <!-- 逆向工程的核心依赖 -->
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                    <!-- 数据库连接池 -->
                    <dependency>
                        <groupId>com.mchange</groupId>
                        <artifactId>c3p0</artifactId>
                        <version>0.9.2</version>
                    </dependency>
                    <!-- MySQL 驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.25</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

(3) Create a configuration file for reverse engineering in the resources directory generatorConfig.xml(the name is fixed and immutable), and add the following content (some labels need to be modified according to the actual situation, just see the comments to modify)

<?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>
    <!-- mybatis-generator:generate -->
    <!--
         targetRuntime: 生成逆向工程的版本
         MyBatis3: 生成带条件的CRUD(豪华尊享版)
         MyBatis3Simple: 生成简单的CRUD(清新简洁版)
    -->
    <context id="atguiguTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是;false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

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

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

        <!-- targetProject:生成Entity类的路径 -->
        <javaModelGenerator targetProject=".\src\main\java"
                            targetPackage="com.jd.wds.pojo">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- targetProject:XxxMapper.xml映射文件生成的路径 -->
        <sqlMapGenerator targetProject=".\src\main\java"
                         targetPackage="com.jd.wds.mapper">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- targetPackage:Mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetProject=".\src\main\java"
                             targetPackage="com.jd.wds.mapper">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--逆向分析的表-->
        <!-- 数据库表名字和我们的entity类对应的映射指定 -->
        <table tableName="t_emp" domainObjectName="Emp" />
        <table tableName="t_dept" domainObjectName="Dept" />
    </context>
</generatorConfiguration>

(4) Download the plug-ins and dependencies configured in pom.xml
insert image description here
(5) Double-click the plug-in for retrograde engineering and wait for completion.
insert image description here
The console output BUILD SUCCESSindicates that the reverse engineering build is successful.
insert image description here
The successful reverse engineering is as follows:
insert image description here

2. Test reverse engineering

Complete project structure:
insert image description here
(1) Create the core configuration file of mybatis under resources mybatis-config.xml, jdbc.properties, log4j.xml
jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=12345678

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration>

    <!-- 将日志信息输出到控制台 -->
    <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
        <!-- 设置日志输出的样式 -->
        <layout class="org.apache.log4j.PatternLayout">
            <!-- 设置日志输出的格式 -->
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%-5p] [method:%l]%n%m%n%n" />
        </layout>
        <!--过滤器设置输出的级别-->
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <!-- 设置日志输出的最小级别 -->
            <param name="levelMin" value="WARN" />
            <!-- 设置日志输出的最大级别 -->
            <param name="levelMax" value="ERROR" />
            <!-- 设置日志输出的xxx,默认是false -->
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <!-- 将日志信息输出到文件,但是当文件的大小达到某个阈值的时候,日志文件会自动回滚 -->
    <appender name="RollingFileAppender" class="org.apache.log4j.RollingFileAppender">
        <!-- 设置日志信息输出文件全路径名 -->
        <param name="File" value="D:/log4j/RollingFileAppender.log" />
        <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->
        <param name="Append" value="true" />
        <!-- 设置保存备份回滚日志的最大个数 -->
        <param name="MaxBackupIndex" value="10" />
        <!-- 设置当日志文件达到此阈值的时候自动回滚,单位可以是KB,MB,GB,默认单位是KB -->
        <param name="MaxFileSize" value="10KB" />
        <!-- 设置日志输出的样式 -->
        <layout class="org.apache.log4j.PatternLayout">
            <!-- 设置日志输出的格式 -->
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss:SSS}] [%-5p] [method:%l]%n%m%n%n" />
        </layout>
    </appender>
</log4j:configuration>

mybatis-config.xml

<?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>
    <!-- 引入外部资源文件 -->
    <properties resource="jdbc.properties"></properties>
    <!-- 设置驼峰匹配,将下划线命名转换为驼峰命名 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 设置包扫描(别名) -->
    <typeAliases>
        <package name="com.jd.wds.pojo"/>
    </typeAliases>
    <!-- 配置环境:可以配置多个环境,default:配置某一个环境的唯一标识,表示默认使用哪个环境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!-- 配置连接信息 -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件:用来配置sql语句和结果集类型等 -->
    <mappers>
        <mapper resource="com/jd/wds/mapper/EmpMapper.xml"/>
    </mappers>
</configuration>

(2) Create a tool class for SqlSessionSqlSessionUtils.java

public class SqlSessionUtils {
    
    
    public static SqlSession getSqlSession(){
    
    
        SqlSession sqlSession = null;
        try {
    
    
            // 1.读取配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            // 2.根据配置文件构建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            // 3.通过sqlSessionFactory创建SqlSession
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return sqlSession;
    }
}

(3) Create test classes and test methods

public class MBGTest {
    
    
    @Test
    public void Test01(){
    
    
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        //查询所有数据
//        List<Emp> list = mapper.selectByExample(null);
//        System.out.println(list);
        //查询empName是张三的员工信息
        EmpExample empExample = new EmpExample();
        empExample.createCriteria().andEmpNameEqualTo("张三");
        List<Emp> list = mapper.selectByExample(empExample);
        System.out.println(list);
    }
}

insert image description here
Watch your feet :

Could not find resource com/jd/wds/mapper/EmpMapper.xml

If during the test, the program reports an error: java.io.IOException: Could not find resource com/jd/wds/mapper/EmpMapper.xml, it is because the idea does not recognize the .xml mapping file under src/main/java, and the mapping file needs to be moved to the resource directory, or mybatis error - java.io.IOException: Could not find resource com/xxx/xxxMapper.xml to view the solution.
I directly moved the mapping file to the resources directory, and then configured it in mybatis-confgi.xml, as shown in the figure:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46081857/article/details/123393758