spring-boot 踩坑程序员

spring-boot与tk-mybatis的集成

2018-09-18  本文已影响1322人  aef5bc56a01e

tk-mybatis是什么鬼

tk-mybatis是Liuzh开发并开源的Mapper项目,是给使用mybatis开发的小伙伴们提供了一些通用的Mapper集合,省去了编写大量的基本sql。
你可以根据需求集成需要的模块。

项目文档

https://github.com/abel533/Mapper/wiki

为什么写这篇文章

如果你看了上面的文档,不免有个疑问,Liuzh提供的文档貌似很详细了,为何你还要写这篇文章呢?其实是因为官方文档只写了一些简单的应用,在开发时不免遇到各种各样的问(大)题(坑)。所以,这篇文章诞生了。

问题汇总

集成及配置

引入包依赖

        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>

配置文件

mapper:
  mappers:
    - tk.mybatis.mapper.common.Mapper
    - tk.mybatis.mapper.common.Mapper2
  notEmpty: true

以上是官方给的配置示例,正常情况下,是没有错滴,但如果你想用官方提供的扩展或者根据自己业务扩展,就会出问题鸟。所以,最好自己定义一个BaseMapper。注意,BaseMapper不要与业务Mapper在同一个目录下!!!
示例:

package com.example.demo.commons;
import tk.mybatis.mapper.additional.idlist.IdListMapper;
import tk.mybatis.mapper.common.Mapper;
public interface BaseMapper<T, PK> extends Mapper<T>, IdListMapper<T, PK> , InsertListMapper<T>{
}

这里Mapper是 BaseSelectMapper BaseInsertMapper BaseUpdateMapper BaseDeleteMapper 的集合;IdListMapper是SelectByIdListMapper和DeleteByIdListMapper的集合;InsertListMapper提供了批量插入的方法

官方还有别的扩展,自己发现吧。

修改后的配置文件

mapper:
  mappers: com.example.demo.commons.BaseMapper #通用基础Mapper类
  not-empty: true
  identity: MYSQL  # 生成id的方法
  enable-method-annotation: true #是否可以用

注意:这时需要在Application类上添加@tk.mybatis.spring.annotation.MapperScan(basePackages=...)以指定要扫描的包

扩展通用方法

mybatis提供了一系列provider,用来提供通用的sql(Mapper.xml对应的sql)
如果需要根据业务扩展,可以参照tk-mybatis的实现方法https://github.com/abel533/Mapper/wiki/5.extend,但有几点要注意:

结尾

暂时遇到这么多需要注意的点,以后如果再遇到会继续补充的。如果有错误的地方,欢迎指正。😄

上一篇下一篇

猜你喜欢

热点阅读