SpringBoot集成Mybatis-Plus

SpringBoot集成Mybatis-Plus

pom.xml导入依赖


<!--包含mybatis-plus、mybaits核心、mybatis-spring-->

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus-boot-starter</artifactId>

            <version>3.1.2</version>

        </dependency>

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus</artifactId>

            <version>3.1.2</version><!--wapper要用这个版本-->

            <!--<version>2.1.8</version>--><!--代码生成器用这个版本-->

        </dependency>

        <!--druid数据库连接池-->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid</artifactId>

            <version>1.1.8</version>

        </dependency>

        <dependency>

            <groupId>com.baomidou</groupId>

            <artifactId>mybatis-plus-generator</artifactId>

            <version>3.1.2</version>

        </dependency>

        <!-- 模板引擎 代码生成 -->

        <dependency>

            <groupId>org.apache.velocity</groupId>

            <artifactId>velocity-engine-core</artifactId>

            <version>2.0</version>

        </dependency>

        <!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->

        <dependency>

            <groupId>org.freemarker</groupId>

            <artifactId>freemarker</artifactId>

            <version>2.3.23</version>

        </dependency>


注意看依赖里面的注释,如果要用到mybatis-plus的wapper,那版本需要是3x以上的,但如果要用Generator代码生成器,我是用的2.1.8的版本,因为3x的版本`import com.baomidou.mybatisplus.generator.config.rules.DbType`这个包导不进去,具体原因也没有做过多的探索,如果有了解的朋友,可以留言给我!一起探讨!



mybatisplus-config.properties配置

注意jdbc.url的时区设置`characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false`


#代码输出基本路径

OutputDir=E:\\code\\java\\demo\\src\\main\\java

        #mapper.xml SQL映射文件目录

OutputDirXml=E:\\code\\java\\demo\\src\\main\\resources

#domain的输出路径

#OutputDirBase=D:/ideaworkspace/hrm-parent/com_likun_cinema/src/main/java

#设置作者

author=ck

#自定义包路径com.zq

parent=com.zq

#数据库连接信息

jdbc.driver=com.mysql.cj.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/ck?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false

jdbc.user=root

jdbc.pwd=root


application.yml配置

可直接复制修改数据库和包名以及mapper.xml的输出路径

注意`driver-class-name: com.mysql.cj.jdbc.Driver`  这里一定要加上cj


spring:

  datasource:

    driver-class-name: com.mysql.cj.jdbc.Driver

    url: jdbc:mysql://127.0.0.1:3306/ck?characterEncoding=utf-8&serverTimezone=GMT%2B8&useSSL=false

    username: root

    password: root

    type: com.alibaba.druid.pool.DruidDataSource

mybatis-plus:

  # 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml

  # 如果是放在resource目录 classpath:/mapper/*Mapper.xml

  mapper-locations: classpath:com/zq/mapper/*Mapper.xml

  #实体扫描,多个package用逗号或者分号分隔

  typeAliasesPackage: com.zq.entity

  global-config:

    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";

    id-type: 0

    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"

    field-strategy: 1

    #驼峰下划线转换

    #db-column-underline: true

    #刷新mapper 调试神器

    #refresh-mapper: true

    #数据库大写下划线转换

    #capital-mode: true

    # Sequence序列接口实现类配置

    #key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator

    #逻辑删除配置(下面3个配置)

    #logic-delete-value: 1

    #logic-not-delete-value: 0

    #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector

    #自定义填充策略接口实现

    #meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler

  configuration:

    map-underscore-to-camel-case: true

    cache-enabled: false

    #配置JdbcTypeForNull

    jdbc-type-for-null: 'null'


启动类中扫描mapper层


@SpringBootApplication

@MapperScan(basePackages = "com.zq.mapper")

public class MySpringbootApplication {

    public static void main(String[] args) {

        SpringApplication.run(MySpringbootApplication.class, args);

    }

}


自定义的模板放在`resources/templates`这个目录下

注意模板里面的涉及的路径一定要修改成自己的路径

controller.java.vm


package ${package.Controller};

import ${package.Service}.${table.serviceName};

import ${package.Entity}.${entity};

import com.zq.query.${entity}Query;

import com.zq.util.AjaxResult;

import com.zq.util.PageList;

import com.baomidou.mybatisplus.plugins.Page;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.ApiOperation;

import io.swagger.annotations.ApiParam;

import java.util.List;

@RestController

@RequestMapping("/${table.entityPath}")

public class ${entity}Controller {

    @Autowired

    public ${table.serviceName} ${table.entityPath}Service;

    /**

    * 保存和修改公用的

    * @param ${table.entityPath}  传递的实体

    * @return Ajaxresult转换结果

    */

    @RequestMapping(value="/save",method= RequestMethod.POST)

    public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){

        try {

            if(${table.entityPath}.getId()!=null){

${table.entityPath}Service.updateById(${table.entityPath});

            }else{

${table.entityPath}Service.insert(${table.entityPath});

            }

            return AjaxResult.me();

        } catch (Exception e) {

            e.printStackTrace();

            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败!"+e.getMessage());

        }

    }

    /**

    * 删除对象信息

    * @param id

    * @return

    */

    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)

    public AjaxResult delete(@PathVariable("id") String id){

        try {

${table.entityPath}Service.deleteById(id);

            return AjaxResult.me();

        } catch (Exception e) {

            e.printStackTrace();

            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败!"+e.getMessage());

        }

    }

    //获取

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)

    public ${entity} get(@PathVariable("id")Long id)

    {

        return ${table.entityPath}Service.selectById(id);

    }

    /**

    * 查看所有

    * @return

    */

    @RequestMapping(value = "/list",method = RequestMethod.GET)

    public List<${entity}> list(){

        return ${table.entityPath}Service.selectList(null);

    }

    /**

    * 分页查询数据

    *

    * @param ${table.entityPath}Query 查询对象

    * @return PageList 分页对象

    */

    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)

    public PageList<${entity}> json(@RequestBody ${entity}Query ${table.entityPath}Query)

    {

        Page<${entity}> page = new Page<${entity}>(${table.entityPath}Query.getPage(),${table.entityPath}Query.getRows());

        page = ${table.entityPath}Service.selectPage(page);

        return new PageList<${entity}>(page.getTotal(),page.getRecords());

    }

}


entity.java.vm


package ${package.Entity};

import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;

import com.baomidou.mybatisplus.annotations.TableField;

import com.baomidou.mybatisplus.annotations.TableName;

import lombok.Data;

import java.io.Serializable;

import java.util.Date;

## 表备注,作者,日期

/**

* @author ${author}

* @since ${date}

*/

## 使用lombok

@Data

@ApiModel(value="${entity}对象")

@TableName("${table.name}")

public class ${entity} implements Serializable {

#foreach($field in ${table.fields})

#if("$!field.comment" != "")

    @ApiModelProperty(value = "${field.comment}")

#end

#if(${field.convert})

#if(${field.keyFlag})

@TableId("${field.name}")

#else

@TableField("${field.name}")

#end

#end

private ${field.propertyType} ${field.propertyName};

#end

}


query.java.vm


package com.zq.query;

import com.zq.common.query.BaseQuery;

/**

*

* @author ${author}

* @since ${date}

*/

public class ${table.entityName}Query extends BaseQuery{

}

```

test.vm

```java

package ${package.Entity};

#foreach($pkg in ${table.importPackages})

import ${pkg};

#end

#if(${swagger2})

import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;

#end

#if(${entityLombokModel})

import lombok.Data;

#end

## 表备注,作者,日期

/**

*

* @author ${author}

* @since ${date}

*/

@Data

@TableName("${table.name}")

@ApiModel(value="${entity}对象")

public class ${entity} implements Serializable {

## ----------  BEGIN 字段循环遍历  ----------

#foreach($field in ${table.fields})

## swagger2字段api

    #if("$!field.comment" != "")

            #if(${field.propertyType} == "Long" || ${field.propertyType} == "Integer")

                #if(${field.keyFlag})

                @ApiModelProperty(value = "${field.comment},新增不传",example="1")

                #else

                @ApiModelProperty(value = "${field.comment}",example="1")

                #end

            #else

            @ApiModelProperty(value = "${field.comment}")

            #end

    #end

private ${field.propertyType} ${field.propertyName};

#end

## ----------  END 字段循环遍历  ----------

## ---------- 使用的lombok,所以后面的get/set都不要 ---------------

}

#foreach($field in ${table.fields})

    #if(${field.keyFlag})

        #set($keyPropertyName=${field.propertyName})

    #end

    #if("$!field.comment" != "")

    /**

    * ${field.comment}

    */

    @ApiModelProperty(value = "${field.comment}")

    #end

    #if(${field.convert})

        #if(${field.keyFlag})

        @TableId("${field.name}")

        #else

        @TableField("${field.name}")

        #end

    #end

private ${field.propertyType} ${field.propertyName};

#end


所有的准备工作都做好了接下来就是真正的代码生成器了

GenteratorCode.java


package com.zq;

import com.baomidou.mybatisplus.generator.AutoGenerator;

import com.baomidou.mybatisplus.generator.InjectionConfig;

import com.baomidou.mybatisplus.generator.config.*;

import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;

import com.baomidou.mybatisplus.generator.config.po.TableInfo;

//import com.baomidou.mybatisplus.generator.config.rules.DbType; //使用时去掉注释 修改pom里面mybatisplus的版本号

import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.*;

/**

* 生成代码的主类

*/

public class GenteratorCode {

    public static void main(String[] args) throws InterruptedException {

        //if(true) return;

        //用来获取Mybatis-Plus.properties文件的配置信息

        ResourceBundle rb = ResourceBundle.getBundle("mybatisplus-config"); //不要加后缀

        String path="/com/zq/";

        AutoGenerator mpg = new AutoGenerator();

        // 全局配置

        GlobalConfig gc = new GlobalConfig();

        gc.setOutputDir(rb.getString("OutputDir"));

        gc.setFileOverride(true);

        gc.setActiveRecord(true);// 开启 activeRecord 模式

        gc.setEnableCache(false);// XML 二级缓存

        gc.setBaseResultMap(true);// XML ResultMap

        gc.setBaseColumnList(false);// XML columList

        gc.setAuthor(rb.getString("author"));

        mpg.setGlobalConfig(gc);

        // 数据源配置

        DataSourceConfig dsc = new DataSourceConfig();

        //dsc.setDbType(DbType.MYSQL);  //使用的时候去掉注释

        dsc.setTypeConvert(new MySqlTypeConvert());

        dsc.setDriverName(rb.getString("jdbc.driver"));

        dsc.setUsername(rb.getString("jdbc.user"));

        dsc.setPassword(rb.getString("jdbc.pwd"));

        dsc.setUrl(rb.getString("jdbc.url"));

        mpg.setDataSource(dsc);

        // 策略配置

        StrategyConfig strategy = new StrategyConfig();

        //strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀

        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略

        //strategy.setInclude(new String[]{"user"}); // 需要生成的表

        strategy.setInclude("user"); // 需要生成的表

        mpg.setStrategy(strategy);

        // 包配置

        PackageConfig pc = new PackageConfig();

        pc.setParent(rb.getString("parent"));

        pc.setController("web.controller");

        pc.setService("service");

        pc.setServiceImpl("service.impl");

        pc.setEntity("entity");

        pc.setMapper("mapper");

        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】

        InjectionConfig cfg = new InjectionConfig() {

            @Override

            public void initMap() {

                Map<String, Object> map = new HashMap<String, Object>();

                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");

                this.setMap(map);

            }

        };

        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

        //controller的输出配置

        focList.add(new FileOutConfig("/templates/controller.java.vm") {

            @Override

            public String outputFile(TableInfo tableInfo) {

                return rb.getString("OutputDir") +path+"web/controller/" + tableInfo.getEntityName() + "Controller.java";

            }

        });

        //query的输出配置

        focList.add(new FileOutConfig("/templates/query.java.vm") {

            @Override

            public String outputFile(TableInfo tableInfo) {

                return rb.getString("OutputDir") +path+"query/" + tableInfo.getEntityName() + "Query.java";

            }

        });

        // 调整 domain 生成目录演示

        focList.add(new FileOutConfig("/templates/entity.java.vm") {

            @Override

            public String outputFile(TableInfo tableInfo) {

                return rb.getString("OutputDir")+path+ "entity/" + tableInfo.getEntityName() + ".java";

            }

        });

        // 调整 xml 生成目录演示

        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {

            @Override

            public String outputFile(TableInfo tableInfo) {

                return rb.getString("OutputDirXml")+path+ "mapper/" + tableInfo.getEntityName() + "Mapper.xml";

            }

        });

        cfg.setFileOutConfigList(focList);

        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,

        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称

        TemplateConfig tc = new TemplateConfig();

        tc.setService("/templates/service.java.vm");

        tc.setServiceImpl("/templates/serviceImpl.java.vm");

        tc.setMapper("/templates/mapper.java.vm");

        tc.setEntity(null);

        tc.setController(null);

        tc.setXml(null);

        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。

        mpg.setTemplate(tc);

        // 执行生成

        mpg.execute();

    }

}


这就是完整的springboot集成mybatis-plus的过程,以及我在其中遇到的一些小坑,不一定适用于全部,但是还是有一定的参考价值!

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

推荐阅读更多精彩内容