当前位置: 移动技术网 > IT编程>开发语言>Java > [springboot 开发单体web shop] 2. Mybatis Generator 生成common mapper

[springboot 开发单体web shop] 2. Mybatis Generator 生成common mapper

2019年11月06日  | 移动技术网IT编程  | 我要评论

mybatis generator tool


在我们开启一个新项目的研发后,通常要编写很多的entity/pojo/dto/mapper/dao..., 大多研发兄弟们都会抱怨,为什么我要重复写crud? 我们为了避免编写一些不必要的重复代码,这节给大家介绍介绍使用一个开源工具,来帮助我们从这种简单枯燥的编码中解救出来。
隆重有请: mybatis通用mapper4

通用mapper都可以极大的方便开发人员。可以随意的按照自己的需要选择通用方法,还可以很方便的开发自己的通用方法。
极其方便的使用mybatis单表的增删改查。
支持单表操作,不支持通用的多表联合查询。
通用 mapper 支持 mybatis-3.2.4 及以上版本。
tips:
各位技术同仁一定要有版本意识哦~
let's code!

create mybatis-generator-tool module

参考中的module创建mybatis-generator-tool.


  • 添加依赖
<?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">
    <parent>
        <artifactid>expensive-shop</artifactid>
        <groupid>com.life-runner</groupid>
        <version>1.0-snapshot</version>
    </parent>
    <modelversion>4.0.0</modelversion>

    <artifactid>mybatis-generator-tool</artifactid>

    <properties>
        <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    </properties>

    <build>
        <plugins>
            <!--springboot 构建可执行fat jars必须的插件,如不添加,在生产环境会有问题-->
            <plugin>
                <groupid>org.springframework.boot</groupid>
                <artifactid>spring-boot-maven-plugin</artifactid>
            </plugin>
            <plugin>
                <groupid>org.mybatis.generator</groupid>
                <artifactid>mybatis-generator-maven-plugin</artifactid>
                <version>1.3.6</version>
                <configuration>
                    <!-- 设置配置文件路径 -->
                    <configurationfile>
                        ${basedir}/src/main/resources/generator/generatorconfig.xml
                    </configurationfile>
                    <!--允许覆盖-->
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <!-- mysql8 驱动-->
                    <dependency>
                        <groupid>mysql</groupid>
                        <artifactid>mysql-connector-java</artifactid>
                        <version>8.0.16</version>
                    </dependency>
                    <!--通用 mapper-->
                    <dependency>
                        <groupid>tk.mybatis</groupid>
                        <artifactid>mapper</artifactid>
                        <version>4.1.5</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

  • 编写配置文件
    根据我们在pom文件中指定的路径:${basedir}/src/main/resources/generator/generatorconfig.xml, 我们需要在项目src=>main=>resource目录下创建generator文件夹,在文件夹下创建文件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>
  <!--引入数据库配置内容-->
  <properties resource="generator/config.properties"/>

  <context id="mysqlcontext" targetruntime="mybatis3simple" defaultmodeltype="flat">
    <!--配置是否使用通用 mapper 自带的注释扩展,默认 true-->
    <!--<property name="usemappercommentgenerator" value="false"/>-->

    <plugin type="tk.mybatis.mapper.generator.mapperplugin">
      <!--设置mapper生成的basic,可自定义-->
      <property name="mappers" value="tk.mybatis.mapper.common.mapper"/>
      <!--大小写转换敏感-->
      <property name="casesensitive" value="true"/>
      <!--引入lombok注解-->
      <property name="lombok" value="getter,setter,tostring"/>
      <!--分隔符定义-->
      <property name="beginningdelimiter" value="`"/>
      <property name="endingdelimiter" value="`"/>
    </plugin>

    <!-- 设置数据库配置 -->
    <jdbcconnection driverclass="${jdbc.driverclass}"
      connectionurl="${jdbc.url}"
      userid="${jdbc.user}"
      password="${jdbc.password}">
    </jdbcconnection>

    <!-- 对应生成的pojo所在包 -->
    <javamodelgenerator targetpackage="com.liferunner.pojo" targetproject="src/main/java"/>

    <!-- 对应生成的mapper所在目录 -->
    <sqlmapgenerator targetpackage="mapper" targetproject="src/main/resources"/>

    <!-- 配置mapper对应的java映射 -->
    <javaclientgenerator targetpackage="com.liferunner.mapper" targetproject="src/main/java" type="xmlmapper"/>

    <!-- 数据库表 -->
    <table tablename="carousel"></table>
    <table tablename="category"></table>
    <table tablename="items"></table>
    <table tablename="items_comments"></table>
    <table tablename="items_img"></table>
    <table tablename="items_param"></table>
    <table tablename="items_spec"></table>
    <table tablename="order_items"></table>
    <table tablename="order_status"></table>
    <table tablename="orders"></table>
    <table tablename="shop_users"></table>
    <table tablename="user_address"></table>
    <table tablename="users"></table>
  </context>
</generatorconfiguration>

我们可以看到一行配置内容:<properties resource="generator/config.properties"/>,这里是为了将我们的数据库连接、账号等信息外置,配置内容如下:

jdbc.driverclass = com.mysql.cj.jdbc.driver
jdbc.url = jdbc:mysql://localhost:3306/expensiveshop?characterencoding=utf-8&usessl\
  =false&useunicode=true&servertimezone=utc
jdbc.user = root
jdbc.password = 12345678

可以看到这里设置的内容就是下属代码中用到的。

...
   <jdbcconnection driverclass="${jdbc.driverclass}"
      connectionurl="${jdbc.url}"
      userid="${jdbc.user}"
      password="${jdbc.password}">
    </jdbcconnection>
...

配置信息大家可以参考:传送门


  • 使用maven测试生成
    执行以下命令:
mybatis-generator-tool>mvn mybatis-generator:generate
[info] scanning for projects...
[info]
[info] ---------------< com.life-runner:mybatis-generator-tool >---------------
[info] building mybatis-generator-tool 1.0-snapshot
[info] --------------------------------[ jar ]---------------------------------
[info]
[info] --- mybatis-generator-maven-plugin:1.3.6:generate (default-cli) @ mybatis-generator-tool ---
[info] connecting to the database
[info] introspecting table carousel
[info] introspecting table category
...
[info] generating record class for table carousel
[info] generating mapper interface for table carousel
[info] generating sql map for table carousel
...
[info] saving file carouselmapper.xml
...
[info] saving file carousel.java
[info] saving file users.java
...
[warning] table configuration with catalog null, schema null, and table shop_users did not resolve to any tables
[info] ------------------------------------------------------------------------
[info] build success
[info] ------------------------------------------------------------------------
[info] total time:  1.374 s
[info] finished at: 2019-11-05t15:40:07+08:00
[info] ------------------------------------------------------------------------

可以看到执行成功,虽然这里执行成功,但是当我们打开文件的时候会发现:

package com.liferunner.pojo;

import java.util.date;
import javax.persistence.*;
import lombok.getter;
import lombok.setter;
import lombok.tostring;

@getter
@setter
@tostring
@table(name = "carousel")
public class carousel {
    /**
     * ����id �û�id
     */
    @id
    private string id;

    /**
     * �û��� �û���
     */
    private string imageurl;
    ...
}

这里出现了乱码问题,这又是怎么回事呢?
没关系,let's bing... 传送门,可以看到有265000条结果,那就说明我们的问题已经有太多的人遇到了,随便点开一个:
bug1
可以看到红框里面的内容我们缺失了,在\expensive-shop\mybatis-generator-tool\src\main\resources\generator\generatorconfig.xml中添加上 <property name="javafileencoding" value="utf-8"/>,重新执行生成命令,可以看到我们的乱码就没有了。

@getter
@setter
@tostring
@table(name = "`carousel`")
public class carousel {
    /**
     * 主键
     */
    @id
    @column(name = "`id`")
    private string id;

    /**
     * 图片 图片地址
     */
    @column(name = "`image_url`")
    private string imageurl;
    ...

tips:
在这一环节先剧透一个bug,否则我担心在后续大家遇到的时候,因为它确实是和common mapper生成相关的。

我们点开生成的users.java,可以看到如下所示:

@getter
@setter
@tostring
@table(name = "users")
public class users {
    @column(name = "user")
    private string user;

    @column(name = "current_connections")
    private long currentconnections;

    @column(name = "total_connections")
    private long totalconnections;
}

可是我们的users表不是这样的呀,这是怎么回事???
让我们分析分析:
1.既然没有用到我们自己的users表,但是又确实通过生成器生成了,那么很明显肯定是mysql数据库中表,这是肯定的。
2.那么问题就来了,它从哪里冒出来的?找它,盘它。
3.到底是哪个数据库中的呢?sys?information_schema?performance_schema?
4.挨个查询,果然:
bug2
可以看到,在performance_schema数据库中有一个users表,那么到底是不是我们生成出来的呢?执行show create table users, 结果如上图,字段和生成出来的是一致的!
5.抓住它了,怎么盘它???

很简单,修改jdbc:mysql://localhost:3306/expensiveshop?nullcatalogmeanscurrent=true&characterencoding=utf-8&usessl =false&useunicode=true&servertimezone=utc,新增上加粗部分就可以了。

nullcatalogmeanscurrent 字面意思很简单,就是说如果是null catalog,我就选择current.因为mysql不支持catalog,我们需要告知mybatis这个特性,设置为true就行了。

按照sql标准的解释,在sql环境下catalog和schema都属于抽象概念,主要用来解决命名冲突问题。
从概念上说,一个数据库系统包含多个catalog,每个catalog又包含多个schema,而每个schema又包含多个数据库对象(表、视图、序列等),反过来讲一个数据库对象必然属于一个schema,而该schema又必然属于一个catalog,这样我们就可以得到该数据库对象的完全限定名称从而解决命名冲突的问题了
从实现的角度来看,各种数据库系统对catalog和schema的支持和实现方式千差万别,针对具体问题需要参考具体的产品说明书,比较简单而常用的实现方式是使用数据库名作为catalog名,oracle使用用户名作为schema名.

bug2-1

可查阅mysql官网说明:

本节我们讲解了如何生成我们想要的,简单和重要又重复的工作我们可以通过工具实现啦,下一次我们将开始实际业务的编码实现.
gogogo.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网