zoukankan      html  css  js  c++  java
  • mybatis Generator生成代码及使用方式

    Article1

    一、为什么要有mybatis

      mybatis 是一个 Java 的 ORM 框架,ORM 的出现就是为了简化开发。最初的开发方式是业务逻辑和数据库查询逻辑是分开的,或者在程序中编写 sql 语句,或者调用 sql 存储过程。这样导致思维需要在语言逻辑和 sql 逻辑之间切换,导致开发效率低下。所以出现了一系列的 ORM 框架,ORM 框架将数据库表和 Java 对象对应起来,当操作数据库时,只需要操作对象的 Java 对象即可,例如设置几个 and 条件,只需要设置几个属性即可。

    二、为什么要有mybatis generator

      虽然说有了 mybatis 框架,但是学习 mybatis 也需要学习成本,尤其是配置它需要的 XML 文件,那也是相当繁琐,而且配置中出现错误,不容易定位。当出现莫名其妙的错误或者有大批量需要生成的对象时,时常会有种生无可恋的感觉在脑中徘徊。故此, mybatis generator 应运而生了。

    它只需要简单配置,即可完成大量的表到 mybatis Java 对象的生成工作,不仅速度快,而且不会出错,可让开发人员真正的专注于业务逻辑的开发。

    官方提供的 mybatis generator 功能比较简单,对于稍微复杂但是开发中必然用到的分页功能、批量插入功能等没有实现,但已经有成熟的插件功能支持。

    我已经将我们平时用的mybatis生成工具放到 github ,其中已集成了分页、批量插入、序列化功能。可到 这里 查看,已经介绍了使用方法。

    三、mybatis generator 生成的文件结构

    关于Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases

    由于我使用的是Mysql数据库,这里需要在准备一个连接mysql数据库的驱动jar包

    以下是相关文件截图:

    和Hibernate逆向生成一样,这里也需要一个配置文件:

    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>
        <!-- 数据库驱动包位置 -->
        <classPathEntry location="D:generatormysql-connector-java-5.1.34.jar" /> 
        <!-- <classPathEntry location="C:oracleproduct10.2.0db_1jdbclibojdbc14.jar" />-->
        <context id="DB2Tables" targetRuntime="MyBatis3">
            <commentGenerator>
                <property name="suppressAllComments" value="true" />
            </commentGenerator>
            <!-- 数据库链接URL、用户名、密码 -->
             <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/my_db?characterEncoding=utf8" userId="root" password="123456"> 
            <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->
            </jdbcConnection>
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
            <!-- 生成模型的包名和位置 -->
            <javaModelGenerator targetPackage="andy.model" targetProject="D:generatorsrc">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
            <!-- 生成的映射文件包名和位置 -->
            <sqlMapGenerator targetPackage="andy.mapping" targetProject="D:generatorsrc">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
            <!-- 生成DAO的包名和位置 -->
            <javaClientGenerator type="XMLMAPPER" targetPackage="andy.dao" targetProject="D:generatorsrc">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
            <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
            <table tableName="kb_city" domainObjectName="KbCity" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
            <!-- <table tableName="course_info" domainObjectName="CourseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
            <table tableName="course_user_info" domainObjectName="CourseUserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> -->
        </context>
    </generatorConfiguration>

    生成语句文件:

    java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite

    备注:

     <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL= 在实际的使用过程中,需要设置utf8格式时区,需要对“&”进行HTML转移字符:
    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/db_recruit?characterEncoding=utf8&amp;serverTimezone=UTC" userId="root" password="123456">

    ---------------------
    作者:tolcf
    来源:CSDN
    原文:https://blog.csdn.net/tolcf/article/details/50835165
    版权声明:本文为博主原创文章,转载请附上博文链接!

    生成的文件包含三类:

    1. Model 实体文件,一个数据库表生成一个 Model 实体;
    2. ModelExample 文件,此文件和实体文件在同一目录下,主要用于查询条件构造;
    3. Mapper 接口文件,数据数操作方法都在此接口中定义;
    4. Mapper XML 配置文件;

    在配置文件中配置好文件的生成路径,并设置好对应的包名,即可生成对应的目录结构和文件。我将生成目录设置为 test 目录,实体包名设置为  com.fengzheng.dao.entity   ,接口包名设置为  com.fengzheng.dao.mapper ,然后生成的文件目录结构如下图所示:

    四、如何编写代码呢

      所有的方法调用都来自于生成的接口文件,在 Spring MVC 中,需要在调用方声明,用一个黑名单接口为例,生成的接口文件为 BlackListIPMapper ,所以在调用方要声明此接口,如下:

    @Autowired
    private BlackListIPMapper blackListipMapper; 

    数据库查询

    查询是最常用功能,如下方法是查询 IP 为某值的记录,如果知道主键的话,可以用  selectByPrimaryKey 方法。

    public BlackListIP get(String ip){
            BlackListIPExample example = new BlackListIPExample();
            example.createCriteria().andIpEqualTo(ip);
            List<BlackListIP> blackListIPList = blackListipMapper.selectByExample(example);
            if(blackListIPList!=null && blackListIPList.size()>0){
                return blackListIPList.get(0);
            }
            return null;
        }

    更新、添加、删除方法调用方法类似,具体可查看相关文档介绍。  

    排序

    public BlackListIP get(String ip){
            BlackListIPExample example = new BlackListIPExample();
            example.setOrderByClause("CREATE_TIME desc"); //按创建时间排序
            example.createCriteria().andIpEqualTo(ip);
            List<BlackListIP> blackListIPList = blackListipMapper.selectByExample(example);
            if(blackListIPList!=null && blackListIPList.size()>0){
                return blackListIPList.get(0);
            }
            return null;
        }

    分页

    public PageInfo list(Account account, PageInfo pageInfo,String startTime,String endTime) {
            account.setIsDel(SysParamDetailConstant.IS_DEL_FALSE);
     
            AccountExample example = getCondition(account,startTime,endTime);
     
            if (null != pageInfo && null != pageInfo.getPageStart()) {
                example.setLimitClauseStart(pageInfo.getPageStart());
                example.setLimitClauseCount(pageInfo.getPageCount());
            }
     
            example.setOrderByClause(" CREATE_TIME desc ");
     
            List<Account> list = accountMapper.selectByExample(example);
     
            int totalCount = accountMapper.countByExample(example);
     
            pageInfo.setList(list);
            pageInfo.setTotalCount(totalCount);
     
            return pageInfo;
        }

    实现 a=x and (b=xx or b=xxx)这样的查询条件  

    虽然自动生成代码很方便,但凡事有利即有弊,mybatis generator 没有办法生成表联查(join)功能,只能手动添加。如下实现了a=x and (b=xx or b=xxx)这样的条件拼接。

    AccountExample accountExample = new AccountExample();
    AccountExample.Criteria criteria = accountExample.createCriteria().andTypeEqualTo("4");
    criteria.addCriterion(String.format(" (ID=%d or ID=%d) ",34,35));
    List<Account> accounts = accountMapper.selectByExample(accountExample);
    return accounts; 

    但是需要修改一点代码,修改 org.mybatis.generator.codegen.mybatis3.model包下的ExampleGenerator的第524行代码,将  method.setVisibility(JavaVisibility.PROTECTED);  改为  method.setVisibility(JavaVisibility.PUBLIC);  

    改动已同步到github上。

    --------------------- 
    作者:风的姿态 
    来源:博客园 
    原文:https://www.cnblogs.com/fengzheng/p/5889312.html
    版权声明:本文为博主原创文章,转载请附上博文链接!

    Article2

    MyBatis generator用数据库表生成数据代码的时候,除了生成实体的POJO以外,会同时生成Example文件,以及在mapper.xml中生成Example的sql语句。

    Example类包含一个内部静态类 Criteria,利用Criteria我们可以在类中根据自己的需求动态生成sql where字句,不用我们自己再修改mapper文件添加或者修改sql语句了,能节省很多写sql的时间。

    下面将介绍几种常用的方法(参考上面的博文,这里没有再总结):

    1.模糊搜索用户名:

    String name = “明”;
    UserExample ex = new UserExample();
    ex.createCriteria().andNameLike(’%’+name+’%’);
    List userList = userDao.selectByExample(ex);

    2.通过某个字段排序:

    String orderByClause = "id DESC";
    UserExample ex = new UserExample();
    ex.setOrderByClause(orderByClause);
    List<User> userList = userDao.selectByExample(ex);

    3.条件搜索,不确定条件的个数:

    UserExample ex = new UserExample();
    Criteria criteria = ex.createCriteria();
    if(StringUtils.isNotBlank(user.getAddress())){
        criteria.andAddressEqualTo(user.getAddress());
    }
    if(StringUtils.isNotBlank(user.getName())){
        criteria.andNameEqualTo(user.getName());
    }
    List<User> userList = userDao.selectByExample(ex);

    4.分页搜索列表:

    pager.setPageNum(1);
    pager.setPageSize(5);
    UserExample ex = new UserExample();
    ex.setPage(pager);
    List<User> userList = userDao.selectByExample(ex);

    ---------------------
    作者:wkj888888
    来源:CSDN
    原文:https://blog.csdn.net/wkj888888/article/details/83748886
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    用PHP编写Hadoop的MapReduce程序
    zookeeper原理
    实现输出h264直播流的rtmp服务器 flash直播服务器
    HTTP Live Streaming直播(iOS直播)技术分析与实现
    谷歌技术"三宝"之BigTable
    谷歌技术"三宝"之谷歌文件系统
    谷歌技术"三宝"之MapReduce
    Ceph分层存储分析
    Ubuntu系统监控cpu memery 磁盘Io次数 IO速率 网卡 运行时间等信息的采集
    java动态加载类和静态加载类笔记
  • 原文地址:https://www.cnblogs.com/ryelqy/p/10721968.html
Copyright © 2011-2022 走看看