《MyBatis代码自动生成器》

建议先看 https://www.jianshu.com/p/c558bc213d0c 《SpringBoot集成MyBatis》我的这篇文章,因为配置环境之类的依赖,在这篇文章中我就不讲了。

接着上篇文章的讲解,如何在SpringBoot中集成代码自动生成器。

简介

我们通过代码自动生成器可以一键生成entity、 dao、mapper相关基础代码,可以有效的节省我们的开发时间,提高效率。
这里我介绍的是生成mapper.xml方式,也可以生成注解方式的代码。

代码自动生成器是通过maven运行的,所以先配置项目pom.xml
maven依赖配置如下:

        <!--Mybatis代码自动生成器-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

org.mybatis.generator插件运行配置:

<!--Mybatis代码自动生成器-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId> mysql</groupId>
                        <artifactId> mysql-connector-java</artifactId>
                        <version> 5.1.39</version>
                    </dependency>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!--允许移动生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆盖 -->
                    <overwrite>true</overwrite>
                    <!-- 自动生成的配置 -->
                    <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                </configuration>
            </plugin>

注意 以上xml配置中有一项

<!-- 自动生成的配置 -->
<configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>

这个是具体你想生成什么样的代码内容以及都生成在什么地方,配置在mybatis-generator.xml这个文件中,在项目的resources目录下创建此文件,内容如下:

<?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>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/apptest" userId="root" password="yu123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.yu.scloud.baseframe.frame.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.yu.scloud.baseframe.frame.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成对应表及类名-->
        <!--<table tableName="stocktradeinfo" domainObjectName="StockTradeInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
        <table tableName="theme" domainObjectName="Theme" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <!--添加属性useActualColumnNames为true,那么生成的对象字段就跟表一样-->
            <property name="useActualColumnNames" value="true"/>
        </table>
        <!--<table tableName="stockTheme" domainObjectName="StockTheme" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
    </context>
</generatorConfiguration>

接着在数据库中创建theme表:

image.png

OK!MyBatis代码自动生成器配置完成了,我们使用maven运行一下吧。成功会
model包中生成Theme.java实体类
dao包中生成ThemeMapper.java接口
resources/mapper目录中生成ThemeMapper.xml映射文件

以上文件生成无误的话,我们创建controller和service使用并测试一下吧。

ThemeAutoGenTestService.java接口

import com.yu.scloud.baseframe.frame.model.Theme;

public interface ThemeAutoGenTestService {

    int insertSelective(Theme record);

    Theme selectByPrimaryKey(Integer id);
}

ThemeAutoGenTestServiceImpl.java实现类__

import com.yu.scloud.baseframe.frame.dao.ThemeMapper;
import com.yu.scloud.baseframe.frame.model.Theme;
import com.yu.scloud.baseframe.frame.service.ThemeAutoGenTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service(value = "themeAutoGenTestService")
public class ThemeAutoGenTestServiceImpl implements ThemeAutoGenTestService {

    @Autowired
    ThemeMapper dao;


    @Override
    public int insertSelective(Theme record) {
        return dao.insertSelective(record);
    }

    @Override
    public Theme selectByPrimaryKey(Integer id) {
        return dao.selectByPrimaryKey(id);
    }
}

MyBatisTestController.java控制器类

import com.github.pagehelper.PageHelper;
import com.yu.scloud.baseframe.frame.model.Theme;
import com.yu.scloud.baseframe.frame.service.ThemeAutoGenTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class MyBatisTestController {


    @Autowired
    private ThemeAutoGenTestService themeAutoGenTestService;//测试通过自动生成器生成代码的例子

    //-------通过代码自动生成器生成的数据库表对象相关类:
    //Theme 实体类
    //ThemeMapper接口  dao
    //ThemeMapper.xml xml映射dao操作数据库
    @ResponseBody
    @PostMapping("/addtheme")
    public int insertTheme(Theme theme)
    {
        return themeAutoGenTestService.insertSelective(theme);
    }
    @ResponseBody
    @GetMapping("/gettheme")
    public Theme getThemeById(int id)
    {
        return themeAutoGenTestService.selectByPrimaryKey(id);
    }

}

启动服务,访问controller接口,dung!!!报错了,数据中包含create_date字段时报错了,应该是String无法转成Date对象的错误,这个问题本不在此篇文章的讲解中,但是遇到了简单讲一下吧。
默认SpringMVC进行covert时,参数中含有Date对象的类型时,是不会自动格式化并转换的,需要我们添加一个formatter的Bean,配置如下:

StringToDateConverter字符串转Date日期对象的转换器

_创建StringToDateConverter.java 字符串转Date日期对象的转换器

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

public class StringToDateConverter implements Converter<String, Date> {

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";

    @Override
    public Date convert(String value) {

        if(StringUtils.isEmpty(value)) {
            return null;
        }

        value = value.trim();

        try {
            if(value.contains("-")) {
                SimpleDateFormat formatter;
                if(value.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);
                }else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }

                Date dtDate = formatter.parse(value);
                return dtDate;
            }else if(value.matches("^\\d+$")) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }


}

创建全局Configuration配置 ,WebConfigBeans.java

import javax.annotation.PostConstruct;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

@Configuration
public class WebConfigBeans {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    /**
     * 增加字符串转日期的功能
     */

    @PostConstruct
    public void initEditableAvlidation() {

        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
        if(initializer.getConversionService()!=null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();

            genericConversionService.addConverter(new StringToDateConverter());

        }

    }

}

好。配置完转换器后,再启动服务,访问接口,可以正常读写数据库了,传递Date对象也不怕报错了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容

  • 手艺人的世界 (脱不花) 手艺是具备一定宏观视野的一种技术、能力。进入一个行业,首先要问:这个行业里最牛逼的人是谁...
    朱坤耀阅读 656评论 0 0
  • 上海去菏泽,中转shangqiu一小时。 车站门口齐聚各大中小有无品牌酒店旅馆; 永和豆浆卖汉堡包卖盖浇饭卖水饺卖...
    包先生阅读 94评论 0 0
  • 又是一个不眠夜,毫无思绪,只是想着这样干躺在床上,不如提笔写写这宁静的夜晚。 来学校已有些时日,过得还挺充实,每个...
    不管不闻不问阅读 252评论 0 1
  • 人生如行路,一路艰辛,一路风景。自己的思想所及,就是自己的人生境界。 今天是2017年的最后一天了...
    珠峰之巅99999阅读 513评论 0 3