• MyBatis Generator 逆向工程插件


    原文地址:http://www.yiidian.com/mybatis/mybatis-generator.html

    1 MyBatis Gernerator插件概述

    官网:http://mybatis.org/generator/

    MyBatis的开发需要程序员自己编写sql语句,MyBatis官方提供逆向工程,可以针对单表自动生成MyBatis执行所需要的代码(Dao接口、Mapper.xml、Pojo等元素),可以让程序员将更多的精力放在繁杂的业务逻辑上。

    之所以强调单表两个字,是因为Mybatis逆向工程生成的Mapper所进行的操作都是针对单表的,也许你可能会觉得那这就有点鸡肋了,但是在大型项目中,很少有复杂的多表关联查询,所以作用还是很大的。

    2 搭建逆向工程,生成代码

    2.1 创建工程,导入依赖

    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
    </dependencies>
    

    2.2 准备jdbc.properties

    在resources建立jdbc.properties,内容如下:

    jdbc.path=D:\reponsitory_boot\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis
    jdbc.username=root
    jdbc.password=root
    

    注意:jdbc.path是mysql驱动包的路径,待会MyBatis逆向工程配置用到

    2.3 逆向工程配置

    在resources配置mybatis-generator-config.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>
        <!--导入属性配置-->
        <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.yiidian.domain" targetProject="D:idea_workspaceyiidianmybatisch02_06_mybatis_generatorsrcmainjava">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
                <!-- 从数据库返回的值被清理前后的空格 -->
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的mapper文件 -->
            <sqlMapGenerator targetPackage="com.yiidian.dao" targetProject="D:idea_workspaceyiidianmybatisch02_06_mybatis_generatorsrcmain
    esources">
                <!-- 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.yiidian.dao"
                                 targetProject="D:idea_workspaceyiidianmybatisch02_06_mybatis_generatorsrcmainjava" type="XMLMAPPER">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
            </javaClientGenerator>
    
    
            <!-- 指定数据库表 -->
            <table schema="mybatis" tableName="t_customer" domainObjectName="Customer" mapperName="CustomerDao"
                   enableCountByExample="false" enableDeleteByExample="false"
                   enableSelectByExample="true" enableUpdateByExample="false"/>
    
        </context>
    </generatorConfiguration>
    

    重点修改的配置解析

    • javaModelGenerator :指定Pojo生成的包名,及存放的目录位置
    • sqlMapGenerator : 指定Mapper映射配置生成的包名,及存放的目录位置
    • javaClientGenerator : 指定Mapper接口生成的包名,及存放的目录位置
    • table :执行需要逆向生成的元素信息,例如 表名,实体名,Mapper映射文件名,Mapper接口名,以及指定Mapper接口是否产生Example查询的相关方法

    table标签的属性

    • schema 数据库名称
    • tableName 表名称
    • domainObjectName 实体类名
    • mapperName Mapper接口名称(注:Mapper映射文件和Mapper接口名称一致)
    • enableCountByExample 是否生成Example条件统计方法
    • enableDeleteByExample 是否生成Example条件删除方法
    • enableSelectByExample 是否生成Example条件查询方法
    • enableUpdateByExample 是否生成Example条件更新方法

    2.4 编写逆向工程执行类

    在test目录建立执行类,用于读取逆向工程配置,生成代码

    package com.yiidian.mybatis;
    
    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;
    
    /**
     * myBatis逆向工程
     * 一点教程网 - www.yiidian.com
     */
    public class MyBatisGeneratorTest {
    
        public void generator() throws Exception{
    
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            //指定 逆向工程配置文件
            InputStream in = MyBatisGeneratorTest.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();
    
        }
        public static void main(String[] args) throws Exception {
            try {
                MyBatisGeneratorTest generatorSqlmap = new MyBatisGeneratorTest();
                generatorSqlmap.generator();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

    2.5 生成后的效果

    file

    3 使用逆向工程生成的Dao方法

    3.1 逆向工程生成的Dao方法

    package com.yiidian.dao;
    import com.yiidian.domain.Customer;
    import com.yiidian.domain.CustomerExample;
    import java.util.List;
    /**
     * 一点教程网 - www.yiidian.com
     */
    public interface CustomerDao {
        int deleteByPrimaryKey(Integer id);
    
        int insert(Customer record);
    
        int insertSelective(Customer record);
    
        List<Customer> selectByExample(CustomerExample example);
    
        Customer selectByPrimaryKey(Integer id);
    
        int updateByPrimaryKeySelective(Customer record);
    
        int updateByPrimaryKey(Customer record);
    }
    

    3.2 insert

    1)测试方法

    /**
     * 测试insert方法
     * 一点教程网 - www.yiidian.com
     */
    @Test
    public void testInsert(){
        SqlSession sqlSession = MyBatisUtils.getSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
    
        Customer cust = new Customer();
        cust.setName("小明");
    
        customerDao.insert(cust);
    
        sqlSession.commit();
        sqlSession.close();
    }
    

    2)执行效果

    file

    可以看到,insert方法会全部字段都插入数据,如果该属性没有赋值,则插入NULL。

    3.3 insertSelective

    1)测试方法

    /**
      * 测试insertSelective方法
      * 一点教程网 - www.yiidian.com
    */
    @Test
    public void testInsertSelective(){
        SqlSession sqlSession = MyBatisUtils.getSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
    
        Customer cust = new Customer();
        cust.setName("小明");
    
        customerDao.insertSelective(cust);
    
        sqlSession.commit();
        sqlSession.close();
    }
    

    2)执行效果
    file

    相对insert方法,insertSelective方法更加灵活些。它能根据属性赋值情况来判断是否插入该字段,这种动态插入方式在项目中更推荐使用。

    3.3 updateByPrimaryKey

    1)测试方法

    /**
     * 测试UpdateByPrimaryKey方法
     * 一点教程网 - www.yiidian.com
     */
    @Test
    public void testUpdateByPrimaryKey(){
        SqlSession sqlSession = MyBatisUtils.getSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
    
        Customer cust = new Customer();
        cust.setId(3);
        cust.setName("小明");
    
        customerDao.updateByPrimaryKey(cust);
    
        sqlSession.commit();
        sqlSession.close();
    }
    

    2)执行效果

    file

    update方法和insert类似,不管该属性有没有赋值,有会更新该字段,叫全字段更新。

    3.4 UpdateByPrimaryKeySelective

    1)测试方法

    /**
     * 测试updateByPrimaryKeySelective方法
     * 一点教程网 - www.yiidian.com
     */
    @Test
    public void testUpdateByPrimaryKeySelective(){
        SqlSession sqlSession = MyBatisUtils.getSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
    
        Customer cust = new Customer();
        cust.setId(3);
        cust.setName("小明");
    
        customerDao.updateByPrimaryKeySelective(cust);
    
        sqlSession.commit();
        sqlSession.close();
    }
    

    2)执行效果
    file

    可以看到,updateByPrimaryKeySelective方法和insertSeletive方法类似,是一种动态更新效果。

    3.5 selectByExample

    /**
     * 测试SelectByExample方法
     * 一点教程网 - www.yiidian.com
     */
    @Test
    public void testSelectByExample(){
        SqlSession sqlSession = MyBatisUtils.getSession();
        CustomerDao customerDao = sqlSession.getMapper(CustomerDao.class);
    
        //1.创建Example对象,Example是MyBatis逆向工程生成的封装了所有查询条件的对象
        CustomerExample customerExample = new CustomerExample();
        //2.添加查询条件
        CustomerExample.Criteria criteria = customerExample.createCriteria();
        //需求:根据name模糊查询
        //criteria.andNameLike("%小%");
        //需求:根据gender查询
        //criteria.andGenderEqualTo("女");
    
        List<Customer> list = customerDao.selectByExample(customerExample);
        System.out.println(list);
    
        sqlSession.close();
    }
    

    Criteria对象可以设置条件非常多,根据表的结构的不同会有不同的可限制条件:
    file

    源码下载:https://pan.baidu.com/s/1PIhaTRc1qAj-BsLON4qj6w

    file

    欢迎关注我的公众号::一点教程。获得独家整理的学习资源和日常干货推送。
    如果您对我的系列教程感兴趣,也可以关注我的网站:yiidian.com

  • 相关阅读:
    pyspark使用及原理
    谷歌地图聚合点使用(GoogleMaps MarkerCluster)
    struts2升级到2.5的配置
    二进制反码补码
    进制转换
    JAVA基础第一章
    TypeError: unhashable type: 'list' 如何解决?
    剪辑模板
    Mysql三天入门(三) 数据库设计的三范式
    Mysql三天入门(三) DBA命令
  • 原文地址:https://www.cnblogs.com/yiidian/p/12401246.html
Copyright © 2020-2023  润新知