从01开始 从01开始
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)

peterjxl

人生如逆旅,我亦是行人
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

    • SpringBoot教程-尚硅谷

      • SpringBoot课程介绍
      • Spring和SpringBoot
      • HelloWorld
      • 了解自动配置原理
      • 底层注解-@Configuration详解
      • 底层注解-@Import导入组件
      • 底层注解-@Conditional条件装配
      • 原生配置文件引入-@ImportResource
      • 底层注解-配置绑定@ConfigurationProperties
      • 自动配置原理
      • 自动配置流程
      • Lombok简化开发
      • DevTools
      • Spring-Initailizr
      • 配置文件-Yaml用法
      • Web开发简介
      • web开发-静态资源规则于定制化
      • 静态资源配置原理
      • Rest映射及源码解析
      • 请求映射原理
      • 常用参数注解使用
      • MatrixVariable:矩阵变量
      • 各种类型参数解析原理
      • Servlet-API参数解析原理
      • Model、Map参数解析原理
      • 自定义对象参数绑定原理
      • 自定义Converter原理
      • 数据响应原理
      • 内容协商原理
      • 基于请求参数的内容原理
      • 自定义MessageConverter原理
      • Thymeleaf初体验
      • web实验-后台管理系统
      • web实验-抽取公共页面
      • web实验-遍历数据
      • 源码分析-视图解析器与视图
      • 拦截器-登录检查与静态资源放行
      • 拦截器的执行时机和原理
      • 单文件和多文件上传的使用
      • 文件上传原理
      • 错误处理机制
      • 错误处理-底层组件源码分析
      • 异常处理流程
      • 几种异常处理原理
      • Web原生对象注入
      • 嵌入式Servlet容器
      • 定制化原理
      • 数据库场景的自动配置分析和整合测试
      • 自定义方式整合Druid
      • 通过starter整合Druid
      • 整合Mybatis
        • 引入starter
        • 自动配置分析
        • 开始使用Mybatis
        • 总结
      • 使用注解整合Mybatis
      • 整合MybatisPlus操作数据库
      • MybatisPlus-列表分页展示
      • 整合Redis
      • 单元测试-Junit5
      • 单元测试-断言机制
      • 单元测试-前置条件
      • 单元测试-嵌套测试
      • 单元测试-参数化测试
      • 指标监控-基本概念
      • 指标监控-配置EndPoint
      • 指标监控-可视化
      • 原理解析-Profile功能
      • 配置文件深入
      • 自定义Starter
      • SpringApplication初始化过程
      • SpringBoot完整启动过程
      • SpringBoot
  • Java并发

  • Java源码

  • JVM

  • 韩顺平

  • Java
  • Java
  • SpringBoot
  • SpringBoot教程-尚硅谷
2023-08-22
目录

整合Mybatis

# 510.整合Mybatis

之前我们使用的JdbcTemplate,轻量级的封装;接下来我们整合Mybatis   ‍

‍

# 引入starter

Mybatis属于第三方技术,因此SpringBoot官方没有提供starter;为此,Mybatis提供了一个,我们可以访问其GitHub地址 (opens new window),可以进入其spring-boot-starter目录,打开其pom.xml文件,就可以看到当前项目的依赖情况:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot</artifactId>
    <version>3.0.3-SNAPSHOT</version>
  </parent>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <name>mybatis-spring-boot-starter</name>
  <properties>
    <module.name>org.mybatis.spring.boot.starter</module.name>
  </properties>
...........
1
2
3
4
5
6
7
8
9
10
11
12
13

​​

‍

我们只需引入其定义的依赖即可:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
1
2
3
4
5

‍

# 自动配置分析

在之前我们使用Mybatis,都是定义一个全局配置文件,SqlSessionFactory,SqlSession和Mapper,我们看看Mybatis是否配置好了。

starter引入了如下依赖:一个是JDBC的,一个是自动配置的,还引入了Mybatis,Mybatis和Spring的整合

​​

‍

我们来看看其自动配置了什么。首先我们看spring.factories:

​​

‍

之前我们说过,SpringBoot启动的时候会自动加载这个文件,然后开启自动配置:

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
1
2
3
4

‍

‍

‍

我们来看看MybatisAutoConfiguration​:

@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisAutoConfiguration implements InitializingBean {

    //.....
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);   
        //.....
    }


    @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        //.....
    }


    @org.springframework.context.annotation.Configuration
    @Import(AutoConfiguredMapperScannerRegistrar.class)
    @ConditionalOnMissingBean({ MapperFactoryBean.class, MapperScannerConfigurer.class })
    public static class MapperScannerRegistrarNotFoundConfiguration
    //.....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

‍

先来说说类上的注解:

  • @ConditionalOnClass​:只有引入了Mybatis的依赖,该配置才生效
  • @ConditionalOnSingleCandidate(DataSource.class)​:有且只有一个数据源的时候,才会生效;
  • @EnableConfigurationProperties​:绑定Mybatis配置,因此如果要配置Mybatis,配置项的前缀就是mybatis。
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {

  public static final String MYBATIS_PREFIX = "mybatis";
//...........
1
2
3
4
5

‍

‍

再看看该自动配置类,注入的bean:

  • ​SqlSessionFactory​,并且配置了数据源
  • SqlSessionTemplate​则相当于是SqlSession​,用来操作数据库的。
  • ​MapperScannerRegistrarNotFoundConfiguration​:相当于是Mapper的扫描配置,会自动扫描用了@Mapper注解的类,我们可以看看其Import的类:
public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

      logger.debug("Searching for mappers annotated with @Mapper");

      List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
      if (logger.isDebugEnabled()) {
        packages.forEach(pkg -> logger.debug("Using auto-configuration base package '{}'", pkg));
      }
    //..........
1
2
3
4
5
6
7
8
9
10
11
12

‍

‍

‍

‍

# 开始使用Mybatis

我们使用Mybatis,来写一个案例,忘了的同学可以复习下:Mybatis | 从01开始 (opens new window)

‍

‍

‍

新建一个实体类:

package com.peterjxl.learnspringbootwebadmin.bean;

import lombok.Data;

@Data
public class Student {
    private Integer id;
    private String name;
    private int gender;
    private int grade;
    private int score;
}
1
2
3
4
5
6
7
8
9
10
11
12

‍

‍

新增一个代理接口:

package com.peterjxl.learnspringbootwebadmin.mapper;

import com.peterjxl.learnspringbootwebadmin.bean.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper {

    Student selectStudentById(Integer id);

}
1
2
3
4
5
6
7
8
9
10
11

‍

‍

新增service层:

package com.peterjxl.learnspringbootwebadmin.service;

import com.peterjxl.learnspringbootwebadmin.bean.Student;
import com.peterjxl.learnspringbootwebadmin.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public Student selectStudentById(Integer id) {
        return studentMapper.selectStudentById(id);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

‍

新增表现层

我们找一个controller,调用service层的方法:

@Controller
public class IndexController {
    @Autowired
    StudentService studentService;

    @GetMapping("/stu")
    public Student getStudentById(@RequestParam("id") Integer id) {
        return studentService.selectStudentById(id);
    }

//.............
1
2
3
4
5
6
7
8
9
10
11

‍

‍

新建全局的配置文件:resources/mybatis/mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
1
2
3
4
5
6
7
8
9

为了方便,我们开启了驼峰式命名的配置。例如数据库中,列的名字是user_id,那么在Java类中只需定义userId,也可绑定值。

ps:也可在yml文件中配置该项,但是这样的话,在yml中就不能指定全局配置文件了,因为用了两种配置方式的话(全局配置文件+yml文件),Mybatis就不知道以哪个为准

‍

新增Mapper配置文件:

<?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.peterjxl.learnspringbootwebadmin.mapper.StudentMapper">

   <select id="selectStudentById" resultType="com.peterjxl.learnspringbootwebadmin.bean.Student">
        select * from students where id = #{id}
   </select>

</mapper>
1
2
3
4
5
6
7
8
9
10
11

‍

‍

修改application.yml文件,增加Mybatis的配置,指定全局配置文件和Mapper文件的位置:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
1
2
3

‍

重启,访问路径,可以看到能正常查询出来数据:

​​

‍

# 总结

使用步骤:

  • 导入starter
  • 编写mapper接口(要标注@Mapper接口)
  • 编写mapper映射文件,绑定mapper接口
  • 在application.yml中指定配置文件的信息(建议不使用全局配置文件)

其实也可以在初始化SpringBoot项目的时候,选择Mybatis的依赖,这样能省略一些步骤:

​​​​

‍

已将本文源码上传到Gitee (opens new window)或GitHub (opens new window) 的分支demo12,读者可以通过切换分支来查看本文的示例代码

在GitHub上编辑此页 (opens new window)
上次更新: 2023/8/23 10:10:57
通过starter整合Druid
使用注解整合Mybatis

← 通过starter整合Druid 使用注解整合Mybatis→

Theme by Vdoing | Copyright © 2022-2023 粤ICP备2022067627号-1 粤公网安备 44011302003646号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式