MyBatis + Spring Boot

本文介绍如何使用MyBatis-Spring-Boot-Starter快速搭建MyBatis应用程序,包括安装配置、使用SqlSession及高级扫描等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyBatis-Spring-Boot-Starter有助于基于Spring Boot快速搭建MyBatis应用程序,使用该模块,可以做到以下几件事情:
1)构建独立的应用程序;
2)降低到几乎为零;
3)更少XML配置文件

安装
     为使用Mybatis-Spring-Boot-Starter模块,仅仅需要在类路径上包含mybatis-spring-boot-autoconfigure.jar文件及其依赖关系(mybatis.jar、mybatis-spring.jar等等)
     如果使用Maven,只要将下述依赖关系添加至pom.xml中:
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.3.1-SNAPSHOT</version>
</dependency>

     如果使用gradle,添加如下至build.gradle:
dependencies {
  compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1-SNAPSHOT")
}

快速启动

     正如也许已经知道的那样,为使用Spring与Mybatis,需要至少一个SqlSessionFactory与至少一个mapper接口。
     Mybatis-Spring-Boot-Starter会:
1)自动检测已存在的DataSource;
2) 创建并注册一个SqlSessionFactory实例,使用SqlSessionFactoryBean传递DataSource作为入参;
3)创建并注册一个SqlSessionFactory获取的SqlSessionTemplate实例
4)自动扫描mappers映射器,将其连接至SqlSessionTemplate,并注册到Spring上下文中,一边可以注入到实体类中

     假设有以下mapper映射器:
@Mapper
public interface CityMapper {

  @Select("SELECT * FROM CITY WHERE state = #{state}")
  City findByState(@Param("state") String state);

}
     仅仅需要创建一个通常的Spring Boot应用程序,并像下面那样注入量映射器(Spring 4.3+版本可用):
@SpringBootApplication
public class SampleMybatisApplication implements CommandLineRunner {

  private final CityMapper cityMapper;

  public SampleMybatisApplication(CityMapper cityMapper) {
  this.cityMapper = cityMapper;
  }

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

  @Override
  public void run(String... args) throws Exception {
  System.out.println(this.cityMapper.findByState("CA"));
  }

} 
     这就是所要做的全部事情,现在应用程序可以像通常的Spring Boot应用程序那样运行。

高级扫描

     Mybatis-Spring-Boot-Starter会默认扫描带有@Mapper注解的映射器,也许会想指定扫描某一个自定义注解或者标记接口。如果是这样的话,那么必须使用@MapperScan注解。
     Mybatis-Spring-Boot-Starter不会启动扫描进程,如果在Spring上下文中找到至少一个MapperFactoryBean,所以如果想要停止扫描,应该直接用@Bean方法注册映射器。

使用SqlSession
     SqlSessionTemplate实例创建并添加至Spring上下文中,如果像下面那样注入实体(Spring 4.3+可用),可以使用MyBatis API:
@Component
public class CityDao {

private final SqlSession sqlSession;

public CityDao(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}

public City selectCityById(long id) {
return this.sqlSession.selectOne("selectCityById", id);
}

}

配置

     和其他Spring Boot应用程序一样,MyBatis-Spring-Boot应用程序的参数存放在application.propertis(或者applicaton.yml)文件之中:
     Mybatis给其特性使用前缀mybatis,可用特性如下表所示:
特性                                             描述
config-location                    MyBatis xml配置文件位置
check-config-location          表示是否对Mybatis xml配置文件执行存在性检测
mapper-locations                Mapper xml配置文件位置
type-aliases-package          寻找类型别名的包(包分隔符为",;\t\n")
type-handlers-package       寻找类型处理器的包(包分隔符为",;\t\n")
executor-type                      执行类型:SIMPLE\REUSE\BATCH
configuration-properties     MyBatis应用程序外部特性,指定的特性可用作MyBatis 配置文件与Mapper文件内占位符
configuration                       MyBatis配置实体类,该特性不能与config-location一起使用

示例:
# application.properties
mybatis.type-aliases-package=com.example.domain.model
mybatis.type-handlers-package=com.example.typehandler
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=30
...

# application.yml
mybatis:
  type-aliases-package: com.example.domain.model
  type-handlers-package: com.example.typehandler
  configuration:
  map-underscore-to-camel-case: true
  default-fetch-size: 100
  default-statement-timeout: 30
...

使用自定义配置

     Mybatis-Spring-Boot-Starter提供使用Java配置的自动配置生成自定义MyBatis配置方式,会自动查找实现ConfigurationCustomizer接口的实体类体类,调用自定义MyBatis配置的方法(1.2.1以上版本可用)
// @Configuration class
@Bean
ConfigurationCustomizer mybatisConfigurationCustomizer() {
  return new ConfigurationCustomizer() {
  @Override
  public void customize(Configuration configuration) {
  // customize ...
  }
  };
}

检测MyBatis组件

     检测实现MyBatis提供的以下接口的实体类
Interceptor
DatabaseIdProvider

参考官网:Spring Boot集成MyBatis
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值