mybatis generator 生成代码学习

为什么要写这篇文章

以前使用mybatis都是做一些很小的demo,基本是简单重复的CRUD操作,觉得一直手工做这些没有技术含量的工作也不是长远之计,所以就一直想有没有相关的插件,后来发现有mybatis generator这类代码生成工具,无奈生成代码较复杂,一时不能看懂,所以写下这文章,一边学习,一边记录

为何使用mybatis generator

mybatis generator可以根据数据库的表或视图,直接帮我们生成java POJO、mapper接口、mapper.xml这三大块文件,里面不仅包含普遍适用的CRUD代码,封装的Example类也可以避免手工进行SQL的where子句条件拼接,学习mybatis generator不仅能帮我们节省工作量,也对我们规范代码起到了很好的帮助

使用的数据表

CREATE TABLE `sys_user` (
    id BIGINT NOT NULL auto_increment COMMENT '用户ID',
    user_name VARCHAR (50) COMMENT '用户名',
    user_password VARCHAR(50) COMMENT '密码',
    user_email VARCHAR (50) COMMENT '邮箱',
    user_info text COMMENT '简介',
    head_img BLOB COMMENT '头像',
    create_time datetime COMMENT '创建时间',
    PRIMARY KEY (id)
);
ALTER TABLE sys_user COMMENT '用户表';

生成准备

配置文件

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="F:\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar"/> -->

    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="">
        </jdbcConnection>

        <!--POJO 实体类-->
        <javaModelGenerator targetPackage="cn.css.mybatis_train.model" targetProject="src\main\java">
            <!--生成SQL带有null判断-->
            <property name="trimStrings" value="true" />
            <!--设置POJO的父类-->
            <!--<property name="rootClass" value="tk.mybatis.simple.model.BaseEntity" />-->
        </javaModelGenerator>

        <!--mapper xml 文件-->
        <sqlMapGenerator targetPackage="cn.css.mybatis_train.mapper"  targetProject="src\main\resources"/>

        <!--DAO 接口类-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.css.mybatis_train.dao"  targetProject="src\main\java"/>

    <!--我们需要生成代码的数据库表-->
        <table tableName="sys_user">
            <generatedKey column="id" sqlStatement="MySql"/>
        </table>
        <!--<table tableName="sys_role">-->
            <!--<generatedKey column="id" sqlStatement="MySql"/>-->
        <!--</table>-->
    </context>
</generatorConfiguration>

Maven依赖和插件

<!-- 集成mybatis generator-->
<dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.3</version>
        </dependency>
</dependencies>

<build>
        <finalName>mybatis_train</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <!-- mbg 的 maven 插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.3</version>
                <configuration>
                    <!--配置文件位置-->
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.38</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.3</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

然后用maven插件的方式运行()
这里写图片描述

PS:除了maven插件的方式外,还可以通过编写java main方法、Eclipse插件等方式得到相同的结果

生成文件和目录结构

这里写图片描述

生成文件内容

Mapper.xml

代码片段:

<sql id="Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>

上面生成的SQL标签作用是提供给select、update这些方法复用,使用include标签调用

  <select id="selectByExampleWithBLOBs" parameterType="cn.css.mybatis_train.model.SysUserExample" resultMap="ResultMapWithBLOBs">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from sys_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" /> <!--使用include标签复用上面的sql-->
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByExample" parameterType="cn.css.mybatis_train.model.SysUserExample" resultMap="BaseResultMap">

xml文件里id为Example_Where_Clause的方法是指封装了where子句的拼接,我们平常使用where时经常是要在where子句中作大量的判断,如:

select * from table where <condition1> and/or <condition2>......

其中涉及到的oredCriteria、criteria可以参考

https://blog.csdn.net/luanlouis/article/details/22726635

简单概括,就是Criteria、oredCriteria是一个筛选条件集合,而criteria则是他们的基本单位
我们可以在额外生成的那个Example类里看到oredCriteria,Criteria属性,一般使用Example类进行SQL拼接

XXXExample.java

除了生成常规的三个文件外,generator还额外生成了一个Example文件,查了下,这个Example文件的作用是辅助我们做一些复杂的CRUD子句拼接,每个生成的Example都与对应的表有所关联,建议保留

简单用法:

private static SqlSessionFactory sqlSessionFactory;

@BeforeClass
public static void init(){
    try {
          Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
          sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
          reader.close();
        } catch (IOException ignore) {
          ignore.printStackTrace();
        }
    }

@Test
public void testExample(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            SysUserExample example = new SysUserExample();
            Calendar startDay = Calendar.getInstance();
            startDay.set(2016,3-1,28);
            Calendar endDay = Calendar.getInstance();
            endDay.set(2016,4-1,28);
            // 查询结果设定distinct
            example.setDistinct(example.isDistinct());
            // 根据时间段查询
            example.or().andCreateTimeBetween(startDay.getTime(), endDay.getTime());
            // 没有使用spring框架的依赖注入,直接将Mapper接口注入sqlsession
            SysUserMapper userMapper = sqlSession.getMapper(SysUserMapper.class);
            List<SysUser> su = userMapper.selectByExample(example);
            su.stream().forEach(p -> System.out.println(p.getId() +" ----- "+p.getUserName()));
        } finally {
            sqlSession.close();
        }

查询结果如下:
查询结果

结尾

mybatis generator 官方文档

http://www.mybatis.org/generator/index.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值