原文:https://github.com/x113773/testall/issues/9

方式一:mybatis-spring-boot-starter
---
这种方式比较简单,具体步骤如下:
1. 首先添加依赖
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
2. application.properties添加如下配置
```
spring.datasource.url=jdbc:mysql://localhost:3306/testall?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123qwe
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations=classpath:/mybatis/*.xml
mybatis.type-aliases-package=com.ansel.testall.mybatis.model
```
3. 自动扫描mapper接口(或者也可以在每个mapper接口上添加@Mapper注解)
在Application.java上添加注解@MapperScan:
```
@SpringBootApplication
@MapperScan("com.ansel.testall.mybatis.mapper")
public class Application extends SpringBootServletInitializer {
...
```
然后就可以使用mybatis-generator生成mapper接口,mapper xml,model了,关于事务详见[这里](url)。

---
方式一解释:
其实mybatis-spring-boot-starter替我们做了大部分配置:(摘自[官方文档](http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/))

> As you may already know, to use MyBatis with Spring you need at least an SqlSessionFactory and at least one mapper interface.
> MyBatis-Spring-Boot-Starter will:
> - Autodetect an existing DataSource.
> - Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean.
> - Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory.
> - Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.

大概翻译一下:
也许你早就知道,为了在spring上使用mybatis你至少需要一个SqlSessionFactory和一个mapper接口。
MyBatis-Spring-Boot-Starter会:
- 自动检测一个现有的DataSource(数据源)
- 通过把DataSource传送给SqlSessionFactoryBean,创建并注册一个SqlSessionFactory实例
- 使用 SqlSessionFactory 作为构造方法的参数来创建一个SqlSessionTemplate 实例
- 自动扫描mapper接口,与SqlSessionTemplate 连接,并它们注册到Spring上下文使它们可以注入到其他beans中。

如果使用方式二的话,就需要显示做出部分配置。

方式二:mybatis-spring
---
这种方式与传统的spring集成mybatis基本一致(下面展示完整的java配置版,部分xml版)

1. 还是首先添加依赖
```
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
```

2. application.properties添加如下配置
```
spring.datasource.url=jdbc:mysql://localhost:3306/testall?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123qwe
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```

3. 添加一个Mybatis的配置类MyBatisConfig.java,里面做的显示配置,基本与方式一中的自动配置一致:
```
package com.ansel.testall.mybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class MyBatisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}

@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.ansel.testall.mybatis.model");

return sqlSessionFactoryBean.getObject();
}

@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}

/**
* 因为添加了spring-boot-starter-
* jdbc依赖,会触发DataSourceTransactionManagerAutoConfiguration这个自动化配置类
* ,自动构造事务管理器,所以若只有一个数据源可以不必进行下面的配置
*
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}

```

4. 添加一个MyBatisMapperScannerConfig.java类,把mapper扫描单独放在这里配置(或者使用方法一第3步中的注解方式也可以)

```
package com.ansel.testall.mybatis;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
// 由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解,而这个注解只能放在类上,所以...
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//因为只有一个sqlSessionFactory,所以下面这个可以不用设置
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.ansel.testall.mybatis.mapper");
return mapperScannerConfigurer;
}

}

```
---
部分xml版配置:
```
<!-- mapper自动扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ansel.testall.mybatis.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
```
```
<!-- 另外一种mapper自动扫描 -->
<mybatis:scan base-package="com.ansel.testall.mybatis.mapper" />
```

Spring Boot 集成 Mybatis的更多相关文章

  1. Spring Boot集成MyBatis开发Web项目

    1.Maven构建Spring Boot 创建Maven Web工程,引入spring-boot-starter-parent依赖 <project xmlns="http://mav ...

  2. 详解Spring Boot集成MyBatis的开发流程

    MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集. spring Boot是能支持快速创建Spring应用的Java框 ...

  3. 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法

    spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...

  4. spring boot集成mybatis(1)

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  5. spring boot集成mybatis(2) - 使用pagehelper实现分页

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  6. spring boot集成mybatis(3) - mybatis generator 配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. spring boot集成MyBatis 通用Mapper 使用总结

    spring boot集成MyBatis 通用Mapper 使用总结 2019年 参考资料: Spring boot集成 MyBatis 通用Mapper SpringBoot框架之通用mapper插 ...

  8. spring boot集成mybatis只剩两个sql 并提示 Cannot obtain primary key information from the database, generated objects may be incomplete

    前言 spring boot集成mybatis时只生成两个sql, 搞了一个早上,终于找到原因了 找了很多办法都没有解决, 最后注意到生成sql的时候打印了一句话: Cannot obtain pri ...

  9. spring boot 集成 Mybatis,JPA

    相对应MyBatis, JPA可能大家会比较陌生,它并不是一个框架,而是一组规范,其使用跟Hibernate 差不多,原理层面的东西就不多讲了,主要的是应用. Mybatis就不多说了,SSM这三个框 ...

  10. spring boot集成mybatis分页插件

    mybatis的分页插件能省事,本章记录的是 spring boot整合mybatis分页插件. 1.引入依赖 <!-- 分页插件pagehelper --> <dependency ...

随机推荐

  1. docker安装hadoop集群

    docker安装hadoop集群?图啥呢?不图啥,就是图好玩.本篇博客主要是来教大家如何搭建一个docker的hadoop集群.不要问 为什么我要做这么无聊的事情,答案你也许知道,因为没有女票.... ...

  2. java反射 顺序输出类中的方法

    java反射可以获取一个类中的所有方法,但是这些方法的输出顺序,并非代码的编写顺序. 我们可以通过自定义一个注解来实现顺序输出类中的方法. 首先,先写一个类,定义增删改查4个方法 public cla ...

  3. javaScript 设计模式系列之一:观察者模式

    介绍 观察者模式又叫发布订阅模式(Publish/Subscribe),一个目标对象管理所有相依于它的观察者对象.该模式中存在两个角色:观察者和被观察者.目标对象与观察者之间的抽象耦合关系能够单独扩展 ...

  4. 使用Linux的alternatives命令替换选择软件的版本

    上周在安装搜索引擎Elasticsearch时,要求安装比较新的java 版本,我选择了java 1.8.0,安装java 成功后使用java -version 发现使用的版本仍旧是1.6.0, 查询 ...

  5. 走进javascript——数组的那些事

    Array构造器 如果参数只有一个并且是Number类型,那么就是指定数组的长度,但不能是NaN,如果是多个会被当做参数列表. new Array(12) // (12) [undefined × 1 ...

  6. rPithon vs. rPython(转)

    Similar to rPython, the rPithon package (http://rpithon.r-forge.r-project.org) allows users to execu ...

  7. String源码解析(二)

    方法的主要功能看代码注释即可,这里主要看函数实现的方式. 1.getChars(char dst[], int dstBegin) /** * Copy characters from this st ...

  8. PHP基础入门(一)---世界上最好用的编程语言

    作为一名程序员,我们应该都听过这样一个梗:PHP编程语言,是世界上最好用的编程语言~~~下面来和大家看一下,什么是PHP↓↓↓ PHP PHP又名超文本预处理器,是一种通用开源脚本语言.PHP主要适用 ...

  9. Java 后台创建word 文档

    ---恢复内容开始--- Java 后台创建 word 文档 自己总结  网上查阅的文档 分享POI 教程地址:http://www.tuicool.com/articles/emqaEf6 方式一. ...

  10. 浅谈C语言指针

    下面就几种情况讨论指针. 一.指针和变量 变量是存储空间的别名,访问形式是直接访问. 指针访问内存地址是间接访问. 使用指针访问内存的场合:1.局部变量,参数传递    2.动态分配内存 指针本身也是 ...