@mapper注解的使用_三分钟让你看懂Springboot 中 Mybatis 的使用

v2-389e8bf0f1238d314564f44fd4b03a39_1440w.jpg?source=172ae18b

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

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

v2-a47f7f3b786e2e9282ce54ad6f5ed25e_b.jpg

一、使用

如果您正在使用Maven,只需将以下依赖项添加到您的pom.xml中:

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

版本自己可选:

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

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

下功能

  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

三、真实使用过程

1、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>

2、配置数据源

直接在application.properties 中

v2-2a96a64d7b4edecfd760974b6ac8eb67_b.jpg

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

v2-d28484ee596073621ffc2dd5e2d2af03_b.jpg

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

Mapper 接口要加@Mapper 注解

MyBatis-Spring-Boot-Starter将默认搜索标记有@Mapper注解的映射器。
您可能需要指定自定义注解或标记界面进行扫描。 如果是这样,你必须使用@MapperScan注解。

v2-c69dbdd4dc1facb8ce641b83f4a4ea8f_b.jpg

默认不用加这个注解

v2-ce142d25c5579211d760f9d71af9a8b0_b.jpg

v2-29ca25dd80f2a3e016b3a976ed037e94_b.jpg

v2-3a7451e69c1c467521ef02b1c12d5c1a_b.jpg
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值