Springboot 中 Mybatis 的使用

官方文档:html

Mybatis开发团队为Spring Boot 提供了 MyBatis-Spring-Boot-Starter 方便使用。spring

要使用MyBatis-Spring-Boot-Starter模块,只须要在类路径中包含 mybatis

mybatis-spring-boot-autoconfigure.jar文件及其依赖项(mybatis.jar,mybatis -spring.jar等) 。app

下面介绍的是我用到的一部分功能,所有功能还请查阅官方文档dom

1、使用

若是您正在使用Maven,只需将如下依赖项添加到您的pom.xml中:spring-boot

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0-SNAPSHOT</version>
</dependency>

版本本身可选:fetch

须要注意的是:在Spring 中使用mybatis 最少须要 一个SqlSessionFactory 和 mapper 接口spa

 

引入MyBatis-Spring-Boot-Starter 模块后 将自动提供以.net

下功能code

  1. 自动检测现有的数据源。
  2. 将建立并注册一个SqlSessionFactory的实例,使用SqlSessionFactoryBean做为输入传递该DataSource
  3. 将建立并注册SqlSessionFactory的SqlSessionTemplate实例。
  4. 自动扫描您的“Mapper”,将它们连接到SqlSessionTemplate并将它们注册到Spring上下文,以便将它们注入到bean中。

就是说,使用了该Starter以后,只须要定义一个DataSource便可,它会自动建立使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate,会自动扫描你的Mappers,链接到SqlSessionTemplate,并注册到Spring上下文中。

 

二 、配置

与其余Spring Boot应用程序同样,MyBatis-Spring-Boot-Application配置参数存储在application.properties(或application.yml)内部。 使用前缀 mybatis

可用的属性有:

  • config-location : MyBatis. xml配置文件的位置。
  • check-config-location: 指示是否执行MyBatis .xml配置文件的存在检查
  • mapper-locations: Mapper. xml配置文件的位置。
  • type-aliases-package : 通常是放在model(或实体类) 上 ,别名替换,默认是去掉包名。
  • type-handlers-package:用于搜索类型处理程序的包所在位置
  • configuration-properties:MyBatis配置的外部化属性。 指定的属性能够用做MyBatis配置文件和Mapper文件的占位符。
  • configuration:一个MyBatis配置bean。 关于可用的属性,请参阅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

 

3、真实使用过程

一、pom中引入 MyBatis-Spring-Boot-Starter

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0-SNAPSHOT</version>
</dependency>

二、配置数据源

直接在application.properties 中

三、在application.properties 中配置Mapper.xml 的扫描

四、编写Mapper接口,和Mapper.xml

Mapper 接口要加@Mapper 注解

MyBatis-Spring-Boot-Starter将默认搜索标记有@Mapper注解的映射器。

您可能须要指定自定义注解或标记界面进行扫描。 若是是这样,你必须使用@MapperScan注解。

默认不用加这个注解

 

 

参考 : https://www.cnblogs.com/larryzeal/p/5874107.html

相关文章
相关标签/搜索