MyBatis逆向工程简单思路

本文介绍了MyBatis逆向工程的概念,包括它的优点和缺点,如自动化CRUD操作但无法处理复杂多表查询。详细阐述了准备工作,如创建Maven工程,添加依赖,配置mybatis-generator-config.xml和jdbc.properties文件,以及spring的applicationContext_dao.xml。最后提醒运行测试时可能遇到的xml重复sql配置问题。
摘要由CSDN通过智能技术生成

MyBatis逆向工程

1、什么是MyBatis逆向工程

​ 使用MyBatis的插件自动的生产数据库操作的文件

2、优点、缺点

优点:自动化,简单的crud不用自己去一步步实现

缺点:稍微复杂的如多表的数据库操作不能够生成

3、准备工作

  1. 创建一个Maven工程
    image-20201111164142780

  2. 添加pom依赖

    <!-- 定义依赖的版本号 -->
        <properties>
            <junit.version>4.12</junit.version>
            <spring.version>5.2.9.RELEASE</spring.version>
            <pagehelper.version>5.1.8</pagehelper.version>
            <servlet-api.version>2.5</servlet-api.version>
            <dubbo.version>2.8.4</dubbo.version>
            <zookeeper.version>3.4.7</zookeeper.version>
            <zkclient.version>0.1</zkclient.version>
            <mybatis.version>3.4.5</mybatis.version>
            <mybatis.spring.version>1.3.1</mybatis.spring.version>
            <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
            <mysql.version>5.1.32</mysql.version>
            <druid.version>1.0.9</druid.version>
            <commons-fileupload.version>1.3.1</commons-fileupload.version>
            <jackson.version>2.9.5</jackson.version>
    
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
        <!-- 定义依赖 -->
        <dependencies>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- Dubbo依赖包 -->
            <dependency>
                <groupId>javassist</groupId>
                <artifactId>javassist</artifactId>
                <version>3.11.0.GA</version>
            </dependency>
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.10</version>
            </dependency>
    
            <!--web基础包 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
    
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis.spring.version}</version>
            </dependency>
            <!-- mybatis分页插件 -->
            <dependency>
                <groupId>com.github.miemiedev</groupId>
                <artifactId>mybatis-paginator</artifactId>
                <version>${mybatis.paginator.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>${pagehelper.version}</version>
            </dependency>
    
    
            <!-- MySql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- 连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
    
    
            <!-- 文件上传组件 -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>${commons-fileupload.version}</version>
            </dependency>
    
            <!-- spring整合rabbitmq -->
            <dependency>
                <groupId>org.springframework.amqp</groupId>
                <artifactId>spring-rabbit</artifactId>
                <version>2.0.1.RELEASE</version>
            </dependency>
    
            <!-- xml解析器通用包:CXF WebService框架 -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.4</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.3</version>
            </dependency>
            <dependency>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
                <version>1.6.1</version>
            </dependency>
            <dependency>
                <groupId>xml-apis</groupId>
                <artifactId>xml-apis</artifactId>
                <version>1.4.01</version>
            </dependency>
    
            <!--shiro-->
            <!--shiro和spring整合-->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.3.2</version>
            </dependency>
            <!--shiro核心包-->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <!--测试-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
    
            <!-- jackson支持包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>
    
            <!--日志包-->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.25</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
            <!--1 mybatis逆向工程核心包-->
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>1.3.7</version>
            </dependency>
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
            </dependency>
            <!--mybatis核心包-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
    
        </dependencies>
    

4、开始

  1. 在resource根目录下创建mybatis-generator-config.xml
    作用:生成指定数据库表dao.java、dao.xml、bean.java文件 注意:需要自己修改

    <?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="jdbc.properties"></properties>
        <!--指定特定数据库的jdbc驱动jar包的位置-->
        <classPathEntry location="${jdbc.path}"/>
    
        <context id="context" targetRuntime="MyBatis3">
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true"/>
                <property name="suppressDate" value="true"/>
            </commentGenerator>
    
            <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
            <jdbcConnection driverClass="${jdbc.driver}"
                            connectionURL="${jdbc.url}"
                            userId="${jdbc.username}"
                            password="${jdbc.password}"/>
    
            <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
                NUMERIC 类型解析为java.math.BigDecimal -->
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
    
            <!--指定包名生成实体类 以及生成的地址 (可以自定义地址,如果路径不存在会自动创建) -->
            <javaModelGenerator targetPackage="com.hjy.domain.factory"
                                targetProject="C:\E_Document\Java\JavaWorkSpace\idea-workspace\ExportProject\MyBatis-Generator\src\main\java">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
                <!-- 从数据库返回的值被清理前后的空格 -->
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的mapper文件 -->
            <sqlMapGenerator targetPackage="com.hjy.dao.factory"
                             targetProject="C:\E_Document\Java\JavaWorkSpace\idea-workspace\ExportProject\MyBatis-Generator\src\main\resources">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
            </sqlMapGenerator>
    
            <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                    type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                    type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                    type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
            -->
            <javaClientGenerator targetPackage="com.hjy.dao.factory"
                                 targetProject="C:\E_Document\Java\JavaWorkSpace\idea-workspace\ExportProject\MyBatis-Generator\src\main\java" type="XMLMAPPER">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
            </javaClientGenerator>
            <!-- 指定数据库表 -->
            <table schema="saas-export" tableName="co_factory" domainObjectName="Factory" mapperName="FactoryDao"
                   enableCountByExample="false" enableDeleteByExample="false"
                   enableSelectByExample="false" enableUpdateByExample="false"/>
        </context>
    </generatorConfiguration>
    
  2. resource根目录下创建jdbc.properties文件
    作用:配置数据库时需要的信息

    # path得修改为自己maven仓库的mysql-connector-java-x.x.x.jar
    jdbc.path=C:\\E_Document\\maven_stroe\\mysql\\mysql-connector-java\\5.1.6\\mysql-connector-java-5.1.6.jar
    # 注意MySql8.0的为com.mysql.cj.jdbc.Driver
    jdbc.driver=com.mysql.jdbc.Driver
    # 数据库
    jdbc.url=jdbc:mysql://localhost:3306/saas-export?serverTimezone=GMT%2B8&amp;useSSL=false&amp;characterEncoding=utf-8
    # MySql的用户名和密码
    jdbc.username=root
    jdbc.password=123456
    
  3. resource的spring目录下创建applicationContext_dao.xml
    作用:读取properties文件连接数据库

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.hjy.dao"/>
    
        <!--读取db.properties文件-->
        <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    
        <!--1.配置数据源-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="url" value="${jdbc.url}"/>
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
    
        <!--2.配置Spring整合Mybatis *** 由Spring创建SqlSessionFactory对象-->
        <!--2.1 配置SqlSessionFactoryBean-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!--注入数据源-->
            <property name="dataSource" ref="dataSource"/>
            <!-- com.wzx.domain.company.Company  company-->
            <property name="typeAliasesPackage" value="com.hjy.domain"/>
            <!-- PageHelper配置 -->
            <property name="plugins">
                <array>
                    <bean class="com.github.pagehelper.PageInterceptor">
                        <property name="properties">
                            <!--使用下面的方式配置参数,一行配置一个 -->
                            <!-- pageNum<=0 时会查询第一页 -->  
                            <!-- 指定数据库方言 -->
                            <value>
                                reasonable=true
                                helperDialect=mysql
                            </value>
                        </property>
                    </bean>
                </array>
            </property>
        </bean>
    
        <!--2.2 配置Dao接口所在包 动态代理 session.getMapper(Dao.class)-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!--指定Dao接口所在包-->
            <property name="basePackage" value="com.hjy.dao"/>
        </bean>
    
    </beans>
    

5、测试

import org.junit.Test;
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.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Generate {

    public void generator() throws Exception {

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指定 逆向工程配置文件
        InputStream in = Generate.class.getClassLoader().getResourceAsStream("mybatis-generator-config.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(in);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                callback, warnings);
        myBatisGenerator.generate(null);
        in.close();

    }

    @Test
    public void test01() throws Exception {
        try {
            Generate generatorSqlmap = new Generate();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

运行后的项目目录

image-20201111170044405

注意

如果多次运行测试类会在dao.xml里生成重复的sql配置代码,dao和bean不受影响

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值