Spring Boot基础学习笔记06:Spring Boot整合MyBatis

一、Spring Boot数据访问概述

在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。
Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。
Spring Boot提供的常见数据库依赖启动器

二、Spring Boot 整合MyBatis

(一)基础环境搭建

1、数据准备

创建数据库、数据表并插入一定的数据

(1)创建博客数据库blog

在Navicat的查询里,通过语句创建博客数据库blog

在这里插入图片描述
在Navicat里打开刚才创建的博客数据库
在这里插入图片描述

(2)在博客数据库里创建文章表t_article

CREATE TABLE `t_article` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章编号',
  `title` varchar(200) DEFAULT NULL COMMENT '文章标题',
  `content` longtext COMMENT '文章内容',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

在这里插入图片描述

(3)在文章表t_article里插入数据记录

INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('3', '安卓开发权威指南', '从入门到精通讲解...');

在这里插入图片描述

(4)在博客数据库里创建评论表t_comment

CREATE TABLE `t_comment` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '评论编号',
  `content` longtext COMMENT '评论内容',
  `author` varchar(200) DEFAULT NULL COMMENT '评论作者',
  `a_id` int(20) DEFAULT NULL COMMENT '关联的文章编号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

在这里插入图片描述

(5)在评论表t_comment里插入数据记录

INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '小明', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', '李文', '3');
INSERT INTO `t_comment` VALUES ('3', '很详细,喜欢', '童文宇', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '钟小凯', '2');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张三丰', '2');
INSERT INTO `t_comment` VALUES ('6', '操作性强,真棒', '唐雨涵', '3');
INSERT INTO `t_comment` VALUES ('7', '内容全面,讲解清晰', '张杨', '1');

在这里插入图片描述

2、创建项目,引入相应启动器

(1)创建Spring Boot项目MyBatisDemo

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查看pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>net.wz.lesson06</groupId>
    <artifactId>mybatisdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MybatisDemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

(2)创建评论实体类Comment

在这里插入图片描述

package net.wz.lesson06;

public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }
}

文章编号aId,使用了驼峰命名法,对应表中的a_id字段
配置文件中必须配置以下语句,否则查出数据为null

mybatis.configuration.map-underscore-to-camel-case=true

(3)创建文章实体类Article

在这里插入图片描述

package net.wz.lesson06;

import java.util.List;

public class Article {
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<Comment> getCommentList() {
        return commentList;
    }

    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", commentList=" + commentList +
                '}';
    }
}

3、编写配置文件

(1)在全局配置文件中进行数据库连接配置

# 配置数据库
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456

在这里插入图片描述

说明:spring.datasource.driver-class-name=com.mysql.jdbc.Driver 数据库驱动配置并非必须

(2)设置数据源类型配置(以阿里巴巴的Druid数据源为例)

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>

在这里插入图片描述

(3)在全局配置文件里覆盖默认参数

在这里插入图片描述

(二)使用注解方式整合MyBatis

1、创建评论映射器接口 - CommentMapper

在这里插入图片描述

package net.wz.lesson06.mapper;

import net.wz.lesson06.bean.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;


@Mapper // 交给Spring容器管理
public interface CommentMapper {
    // 按照编号查询记录
    @Select("select * from t_comment where id = #{id}")
    Comment findById(Integer id);

    // 查找全部记录
    @Select("select * from t_comment")
    List<Comment> findAll();

    // 插入记录
    @Insert("insert into t_comment values(#{id}, #{content}, #{author}, #{aId})")
    int insertComment(Comment comment);

    // 更新记录
    @Update("update t_comment set content = #{content}, author = #{author} where id = #{id}")
    int updateComment(Comment comment);

    // 删除记录
    @Delete("delete from t_comment where id = #{id}")
    int deleteComment(Integer id);
}

2、在测试类编写测试方法,测试评论映射器接口

点开默认的测试类

在这里插入图片描述
注入评论映射器(如果不设置required = false,变量commentMapper会出现红色波浪线报错)

在这里插入图片描述

(1)创建测试方法testFindById()

在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述

(2)创建测试方法testFindAll()

在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述

(3)创建测试方法testInsertComment()

在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
在这里插入图片描述

(4)创建测试方法testUpdateComment()

修改刚才插入的第8条记录
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述

(5)创建测试方法testDeleteComment()

删除刚才插入的第8条记录
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
在这里插入图片描述

(三)使用配置文件方式整合MyBatis

1、创建Mapper接口文件 - ArticleMapper

在这里插入图片描述

package net.wz.lesson06.mapper;

import net.wz.lesson06.bean.Article;
import org.apache.ibatis.annotations.Mapper;


@Mapper
public interface ArticleMapper {
    Article findArticleById(Integer id);
    int updateArticle(Article article);
}

2、创建映射器配置文件ArticleMapper.xml

在resources目录里创建mapper目录,在mapper目录里创建ArticleMapper.xml
在这里插入图片描述

<?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="net.hw.lesson06.mapper.ArticleMapper">
    <!--按id查询记录,文章表与评论表关联查询-->
    <select id="findArticleById" resultMap="articleWithComment">
        SELECT a.*, c.id c_id, c.content c_content, c.author, c.a_id
        FROM t_article a, t_comment c
        WHERE a.id = c.a_id AND a.id = #{id}
    </select>

    <!--结果集,一篇文章对应多个评论构成的集合-->
    <resultMap id="articleWithComment" type="Article">
        <id property="id" column="id"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <collection property="commentList" ofType="Comment">
            <id property="id" column="c_id"/>
            <result property="content" column="c_content"/>
            <result property="author" column="author"/>
            <result property="aId" column="a_id"/>
        </collection>
    </resultMap>

    <!--更新记录-->
    <update id="updateArticle" parameterType="Article">
        UPDATE t_article
        <set>
            <if test="title != null and title != ''">
                title = #{title},
            </if>
            <if test="content != null and content != ''">
                content = #{content}
            </if>
        </set>
        WHERE id = #{id}
    </update>
</mapper>

3、在全局配置文件里配置映射器配置文件路径

在这里插入图片描述

4、在测试类编写测试方法,测试文章映射器

注入文章映射器
在这里插入图片描述

(1)创建测试方法testFindArticleById()

在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述

(2)创建测试方法testUpdateArticle()

在这里插入图片描述运行测试方法,查看结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值