Spring BootV06:Spring Boot整合MyBatis

一、Spring Boot 整合MyBatis
(一)基础环境搭建
1、数据准备
创建数据库、数据表并插入一定的数据
(1)创建博客数据库blog
在这里插入图片描述
(2)在博客数据库里创建文章表t_article
在这里插入图片描述
(3)在文章表t_article里插入数据记录
在这里插入图片描述
(4)在博客数据库里创建评论表t_comment
在这里插入图片描述
(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
在这里插入图片描述
引入MySQL和MyBatis的依赖启动器
在这里插入图片描述
查看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.tjl.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.tjl.lesson06.bean;

/**
 * 功能:评论实体类
 * 作者:谭金兰
 * 日期:2021年05月10日
 */
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 +
                '}';
    }
}

(3)创建文章实体类Article
在这里插入图片描述

package net.tjl.lesson06.bean;

import java.util.List;

/**
 * 功能:文章实体类
 * 作者:谭金兰
 * 日期:2021年05月10日
 */
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
spring.datasource.url=jdbc:mysql://localhost:3306/blog?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=forget

(2)设置数据源类型配置(以阿里巴巴的Druid数据源为例)
在这里插入图片描述
(3)在全局配置文件里覆盖默认参数
在这里插入图片描述
(二)使用注解方式整合MyBatis
1、创建Mapper接口CommentMapper
在这里插入图片描述

package net.tjl.lesson06.mapper;

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

import java.util.List;

/**
 * 功能:评论映射器接口
 * 作者:谭金兰
 * 日期:2021年05月10日
 */
@Mapper  // 由Spring管理的MyBatis接口
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、在测试类编写测试方法
在这里插入图片描述
(1)创建测试方法testFindById()
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
运行时出现了两个问题,一个是deprecate警告,一个是映射问题。
要避免deprecate警告就需要修改application.properties的spring.datasource.driver-class-name的属性
在这里插入图片描述
测试通过,但是输出结果有个小问题,文章编号aId的值为null。为什么呢?因为aId属性对应的是评论表中的a_id字段,需要在全局配置文件里对MyBatis进行一个转换配置:mybatis.configuration.map-underscore-to-camel-case=true
在这里插入图片描述
再运行测试方法,查看结果
在这里插入图片描述
(2)创建测试方法testFindAll()
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
(3)创建测试方法testInsertComment()
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
(4)创建测试方法testUpdateComment()
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
(5)创建测试方法testDeleteComment()
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述
(三)使用配置文件方式整合MyBatis
1、创建Mapper接口文件 - ArticleMapper
在这里插入图片描述
在这里插入图片描述
2、创建映射器配置文件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()
在这里插入图片描述
运行测试方法,查看结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值