SpringBoot(36) — SpringBoot整合MyB

2021-11-02  本文已影响0人  奔跑的佩恩

前言

在上一节中我们大致讲了MyBatisMapper使用,有兴趣的同学可参考
SpringBoot(35) — MyBatis之xml方式加载Mapper(2)
今天让我们来具体讲解下SpringBoot如何整合MyBatis

今天涉及知识有:

  1. MyBatis整合前准备
  2. MyBatis依赖
  3. MyBatis详细接入
    3.1 对应 demo 数据表的实体类
    3.2 dao 包下新建 dao 接口类
    3.3 controller 包下新建 controller 类
    3.4 资源文件夹下建 mapper 的 xml 文件
    3.5 配置文件中做Mysql和MyBatis的配置
    3.6 项目代码配置文件中添加相关扫描配置
  4. 测试
  5. 项目结构图

先来波测试结果图


image.png

一. MyBatis 整合前准备

我使用的是mysql数据库,所以在一起开始之前先要打开你的mysql数据库服务
这里我开启了mysql数据库,并在test_pro数据库中新建了demo数据表,具体展示如下:

image.png

二. MyBatis 依赖

在新建的springBoot项目的pom.xml文件中添加MyBatis相关依赖:

        <!-- mysql数据库连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- druid(阿里德鲁伊)连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

        <!-- 数据库连接spring-boot-starter-jdbc的依赖(数据库连接驱动) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--  mybatis框架 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--缺少此jar包,导致@Mapper注解无效-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>

三. MyBatis 详细接入

3.1 对应 demo 数据表的实体类

这里我们先对应demo表建一个数据实体类Student,代码如下:

/**
 * Title:
 * description:
 * autor:pei
 * created on 2019/9/3
 */
@Data
@Component("Student")
public class Student {

    private int id;

    private String name;

    private int age;

}

其中@Data为省略各种setget方法的注解。@Component("Student")IoC加载前的标记。

3.2 dao 包下新建 dao 接口类

接着我们建立dao包,在其下新建dao接口类 —— StudentDao,代码如下:

上一篇 下一篇

猜你喜欢

热点阅读