spring-boot集成mybatis三剑客

Mybatis与Jpa的选择

Jpa的使用非常简洁,开发效率非常高,国际范围内有更多人支持。
但是在中国,有很多人使用Mybatis。

SpringBoot整合Mybatis

安装依赖

文档

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
dependencies {
  compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3")
}

项目配置

# 配置数据库与数据库连接驱动
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/MoocMall?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: pass
    driver-class-name: com.mysql.jdbc.Driver

通过注解的方式使用Mybatis

public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;
}
@Mapper
public interface CategoryMapper {
    @Select("select * from category where id = #{id}")
    Category selectByPrimaryKey(Integer id);
}

通过配置,测试categoryMapper.selectByPrimaryKey("xxxx")的返回值中部分字段(parentId、sortOrder、createTime、updateTime)值为null,这是因为POJO与数据库的映射没有匹配。可以通过配置mybatis的map-underscore-to-camel-case为ture解决。

spring:
  ...
mybatis:
  configuration:
    map-underscore-to-camel-case: true
    # 控制台日志配置
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Mybatis的mapper组件需要添加@Mapper注解才能被Spring识别,为了方便可以统一在Application的main函数添加mapper包的自动扫描:

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.mall.entities.dao")
public class MallApplication {

    public static void main(String[] args) {
        SpringApplication.run(MallApplication.class, args);
    }

}

IDEA的配置

自动刷新Maven & Gradle依赖

  • Build,Excution,Deployment->Build Toold->Maven->Importing
    • Build,Excution,Deployment->Build Toold->Gradle

自动倒包

  • 手动导入:Option + Enter
  • 配置自动:Editor->General->Auto Import

通过XML配置使用Mybatis

public interface CategoryMapper {
    Category selectByPrimaryKey(Integer id);
}

指定XML文件扫描路径

# application.yml
spring:
  ...
mybatis:
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 配置XML文件的扫描路径
  mapper-locations: classpath:mappers/*.xml

手写Mybatis XML:
查看文档,XML格式

<!--声明-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xx.xxx.entities.dao.CategoryMapper">
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultType="com.xx.xxx.entities.Category">
    select * from category
    where id = #{id,jdbcType=INTEGER}
  </select>
</mapper>

不建议使用select * ...:

<!--声明-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xx.xxx.entities.dao.CategoryMapper">
  <sql id="Base_Column_List">
    id, parent_id, name, status, sort_order, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultType="com.xx.xxx.entities.Category">
    select
    <include refid="Base_Column_List" />
    from mall_category
    where id = #{id,jdbcType=INTEGER}
  </select>
</mapper>

mybatis-generator

生成器的原理:连接数据库 -> 获取表结构 -> 生成文件

安装依赖

文档

<plugin>
  <groupId>org.mybatis.generator</groupId>
  <artifactId>mybatis-generator-maven-plugin</artifactId>
  <version>1.4.0</version>
</plugin>

执行命令:mvn mybatis-generator:generate

添加配置文件:src/main/resources/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>
    <!--配置connector的绝对路径-->
    <classPathEntry location="/Users/lrliang/Desktop/mysql-connector-java-5.1.6.jar" />

    <context id="DB2Tables" targetRuntime="MyBatis3">

        <!--多次生成XML文件时,覆盖文件,而不是追加xml内容-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />

        <!--去掉生成文件中的注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库连接配置-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/Mall?characterEncoding=utf-8"
                        userId="root"
                        password="pass">
        </jdbcConnection>

        <!--设置为false,区分Integer,Long,BigDecimals-->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--配置生成的Entity文件的路径-->
        <javaModelGenerator targetPackage="com.xx.xxx.entities" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--生成Mybatis XML文件存放的路径-->
        <sqlMapGenerator targetPackage="mappers"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--生成src下的MapperBean文件路径-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xx.xxx.entities.dao"  targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--数据库表配置-->
        <table tableName="order" domainObjectName="Order" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
    </context>
</generatorConfiguration>

配置重复生成的文件覆盖原先生成的文件

<plugin>
   <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>

    <configuration>
        <overwrite>true</overwrite>
    </configuration>
</plugin>

生成的文件

Category

public class Category {
    private Integer id;

    private Integer parentId;

    private String name;

    private Boolean status;

    private Integer sortOrder;

    private Date createTime;

    private Date updateTime;

    //getter & setter(可以手动删除,使用Lombok @Data注解)
    ...
}

CategoryMapper

public interface CategoryMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Category record);

    int insertSelective(Category record);

    Category selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Category record);

    int updateByPrimaryKey(Category record);

    List<Category> selectAll();
}

Mybatis Plugin: 在IDE中将Mapper文件与XML文件关联起来

Mybatis Plugin已经开始收费,可以使用替代版:Free-Mybatis-plugin

Mybatis PageHelper:Mybatis通用分页插件

国人开发、开源的Mybatis通用分页插件:文档及源代码

安装依赖:

<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.2.4</version>
</dependency>
<!--pagehelper-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>

使用案例:

    @Override
    public ResponseVo<PageInfo> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIds = new HashSet<>();
        if (categoryId != null) {
            categoryIds = categoryService.findSubCategoryIds(categoryId);
            categoryIds.add(categoryId);
        }

        // 只需要在需要分页的地方加上PageHelper.startPage
        PageHelper.startPage(pageNum, pageSize);
        final List<Product> productList = productMapper.selectByCategoryIdSet(categoryIds);
        List<ProductVo> productVoList = productList
                .stream()
                .map(this::product2ProductVo)
                .collect(Collectors.toList());

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