• 21. Spring Boot 整合 MyBatis



    21.1 需求说明/图解

    1. 将 Spring Boot 和 MyBatis 整合
    2. 查询出一条数据

    在这里插入图片描述


    21.2 综合案例

    21.2.1 代码+配置实现

    21.2.1.1 创建数据库和表
    CREATE DATABASE `springboot_mybatis` 
    
    USE `springboot_mybatis` 
    
    CREATE TABLE `monster` (
    `id` INT NOT NULL AUTO_INCREMENT, 
    `age` INT NOT NULL, 
    `birthday` DATE DEFAULT NULL, 
    `email` VARCHAR(255) DEFAULT NULL, 
    `gender` CHAR(1) DEFAULT NULL, 
    `name` VARCHAR(255) DEFAULT NULL, 
    `salary` DOUBLE NOT NULL,
    PRIMARY KEY (`id`)
    ) CHARSET=utf8
    
    SELECT * FROM `monster`
    
    INSERT INTO monster VALUES(NULL, 20, '2000-11-11', 'nmw@sohu.com', '男', '牛魔王', 5000.88);
    INSERT INTO monster VALUES(NULL, 10, '2011-11-11', 'bgj@sohu.com', '女', '白骨精', 8000.88);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    21.2.1.2 创建 springboot-mybatis 项目,使用灵活的方式创建 maven
    • 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
    
        <groupId>com.xjsgroupId>
        <artifactId>springboot-mybatisartifactId>
        <version>1.0-SNAPSHOTversion>
    
        
        <parent>
            <artifactId>spring-boot-starter-parentartifactId>
            <groupId>org.springframework.bootgroupId>
            <version>2.5.3version>
        parent>
    
        
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.mybatis.spring.bootgroupId>
                <artifactId>mybatis-spring-boot-starterartifactId>
                <version>2.2.2version>
            dependency>
    
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-configuration-processorartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
            dependency>
    
        dependencies>
    
    project>
    
    • 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
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    21.2.1.3 创建 resources/application.yml , 配置数据源参数,并完成 Spring Boot 项目启动测试
    server:
      port: 9090
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/springboot_mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
        username: root
        password: hsp
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    21.2.1.4 切换数据源为 druid
    • 修改 pom.xml (引入 druid依赖 )
    • 并加入配置文件 com/xjs/springboot/mybatis/config/DruidDataSourceConfig.java
    • 完成测试
    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.1.17version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    package com.xjs.springboot.mybatis.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.sql.DataSource;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     */
    @Configuration
    public class DruidDataSourceConfig {
    
        //编写方法,注入DruidDataSource
        @ConfigurationProperties("spring.datasource")
        @Bean
        public DataSource dataSource() {
            DruidDataSource druidDataSource = new DruidDataSource();
            return druidDataSource;
    
        }
    
    }
    
    
    • 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
    21.2.1.5 bean
    • 创建 com/xjs/springboot/mybatis/bean/Monster.java
    • 回顾一下 mybatis 和 ssm项目整合
    package com.xjs.springboot.mybatis.bean;
    
    import lombok.Data;
    
    import java.util.Date;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     */
    @Data
    public class Monster {
        private Integer id;
        private Integer age;
        private Date birthday;
        private String email;
        private String name;
        private String gender;
        private Double salary;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    21.2.1.6 mapper 接口
    • 创建 com/xjs/springboot/mybatis/mapper/MonsterMapper.java
    package com.xjs.springboot.mybatis.mapper;
    
    import com.xjs.springboot.mybatis.bean.Monster;
    import org.apache.ibatis.annotations.Mapper;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     *
     * 在Mapper接口使用 @Mapper 就会扫描,并将Mapper接口对象注入
     */
    @Mapper
    public interface MonsterMapper {
    
        //编写方法,根据 id 返回 Monster对象
        public Monster getMonsterById(Integer id);
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    21.2.1.7 Mapper.xml 文件
    • 创建 src/main/resources/mapper/MonsterMapper.xml
    • 文件模板从 mybatis 官方文档拷贝
    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.xjs.springboot.mybatis.mapper.MonsterMapper">
    
        
        <select id="getMonsterById" resultType="Monster">
            SELECT * FROM `monster` WHERE id=#{id}
        select>
    
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    21.2.1.8 创建 service 层
    • 创建 com/xjs/springboot/mybatis/service/MonsterService.java
    package com.xjs.springboot.mybatis.service;
    
    import com.xjs.springboot.mybatis.bean.Monster;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     */
    public interface MonsterService {
    
        //根据 id 返回 Monster对象
        public Monster getMonsterById(Integer id);
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 创建 com/xjs/springboot/mybatis/service/impl/MonsterServiceImpl.java
    package com.xjs.springboot.mybatis.service.impl;
    
    import com.xjs.springboot.mybatis.bean.Monster;
    import com.xjs.springboot.mybatis.mapper.MonsterMapper;
    import com.xjs.springboot.mybatis.service.MonsterService;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     */
    @Service
    public class MonsterServiceImpl implements MonsterService {
    
        //装配MonsterMapper
        @Resource
        private MonsterMapper monsterMapper;
    
        @Override
        public Monster getMonsterById(Integer id) {
            return monsterMapper.getMonsterById(id);
        }
    }
    
    
    • 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
    21.2.1.9 Controller
    • 创建 com/xjs/springboot/mybatis/controller/MonsterController.java
    package com.xjs.springboot.mybatis.controller;
    
    import com.xjs.springboot.mybatis.bean.Monster;
    import com.xjs.springboot.mybatis.service.MonsterService;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.annotation.Resource;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     */
    @Controller
    public class MonsterController {
    
        //装配MonsterService
        @Resource
        private MonsterService monsterService;
    
        @GetMapping("/monster")
        @ResponseBody
        public Monster getMonsterById(@RequestParam(value = "id") Integer id) {
    
            Monster monster = monsterService.getMonsterById(id);
            return monster;
        }
    
    }
    
    
    • 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
    • 31
    • 32
    • 33
    21.2.1. 10 修改 resources/application.yml ,指定 mybatis 的配置参数
    server:
      port: 9090
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/springboot_mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
        username: root
        password: hsp
    
    mybatis:
      #指定要扫描的 XxxMapper.xml文件
      mapper-locations: classpath:mapper/*.xml
    
      #方式一
      #通过 config-location 可以指定 mybatis-config.xml文件,可以以传统的方式来配置mybatis
    #  config-location: classpath:mybatis-config.xml
    
      #方式二
      #我们也可以直接在 application.yml 进行配置
      #举例说明:
      #1.比如配置原来的 类型别名- typeAliases
      #2.配置输出底层的原生sql (标准日志输出)
      #3.还有其他配置,用到再说...
      type-aliases-package: com.xjs.springboot.mybatis.bean
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
      #说明:配置mybatis的两种方式的选择:
      #如果配置比较简单,就直接在 application.yml文件中配置即可
      #如果配置内容比较多,也可以单独的做一个 application.yml 进行配置
    
    • 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

    21.2.2 测试页面效果

    • 完成测试
    • 浏览器: http://localhost:9090/monster?id=1

    在这里插入图片描述


    21.3 注意事项和细节说明(解决时区问题)

    1. spring boot 整合 mybatis 取出的日期,出现 8 小时时差 解决方案

    在这里插入图片描述

    package com.xjs.springboot.mybatis.bean;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import lombok.Data;
    
    import java.util.Date;
    
    /**
     * @Author: 谢家升
     * @Version: 1.0
     */
    @Data
    public class Monster {
        private Integer id;
        private Integer age;
        //通过注解来解决时区问题
        //GMT 就是格林尼治标准时间
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        private Date birthday;
        private String email;
        private String name;
        private String gender;
        private Double salary;
    }
    
    
    • 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
    • 完成测试

    在这里插入图片描述


  • 相关阅读:
    微信小程序商城搭建鲜花销售系统+后台管理系统|前后分离VUE.js
    Mysql之存储引擎
    go-kit-consul client服务发现源码分析
    数据结构:KMP算法的原理图解和代码解析
    ubantu(linux)下安装qt6遇到的问题
    Paper reading:Fine-Grained Head Pose Estimation Without Keypoints (CVPR2018)
    Mybatis从零开始创建
    C专家编程 第11章 你懂得C,所以C++不再话下 11.1 初识OOP
    es-head安装启动
    怎么解决404异常,接口路径没写错(语言-java)
  • 原文地址:https://blog.csdn.net/weixin_60766221/article/details/126408622