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

一、基础环境搭建

1 准备数据库

(1)创建数据库blog

在这里插入图片描述

(2)创建文章表t_article

在这里插入图片描述

(3)创建评论表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;

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

  • 创建Spring Boot项目MyBatisDemo
    引入MySQL和MyBatis的依赖启动器

(1)创建评论实体类Comment

在这里插入图片描述

package net.yc.lesson06.bean;

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.yc.lesson06.bean;

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)在全局配置文件中进行数据库连接配置

  • properties
    在这里插入图片描述

  • yaml
    在这里插入图片描述

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

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>
  • 注入依赖
    在这里插入图片描述

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

在这里插入图片描述

二、使用注解方式整合MyBatis

1、创建Mapper接口CommentMapper

在这里插入图片描述

package net.yc.lesson06.mapper;

import net.yc.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、在测试类编写测试方法

在这里插入图片描述

package net.yc.lesson06;

import net.yc.lesson06.bean.Comment;
import net.yc.lesson06.mapper.CommentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MybatisDemoApplicationTests {

    @Autowired(required = false)
    private CommentMapper commentMapper;

    @Test
    void contextLoads() {
    }

    @Test
    public void testFindById() {
        Integer id = 1;
        Comment comment = commentMapper.findById(id);
        if (comment != null) {
            System.out.println(comment);
        } else {
        System.out.println("编号为【"+id+"】的评论未找到!");
        }
    }

    @Test
    public void testFindAll() {
        List<Comment> comments = commentMapper.findAll();
        for (Comment comment : comments) {
            System.out.println(comment);
        }
    }

    @Test
    public void testInsertComment() {
        // 创建评论对象
        Comment comment = new Comment();
        comment.setId(8);
        comment.setContent("借鉴,分享,学习。");
        comment.setAuthor("烟火");
        comment.setaId(2);
        // 插入评论记录
        int count = commentMapper.insertComment(comment);
        // 判断是否插入成功
        if (count > 0) {
            System.out.println("评论添加成功!");
        } else {
            System.out.println("评论添加失败!");
        }
    }

    @Test
    public void testUpdateComment() {
        // 获取第8条评论
        Comment comment = commentMapper.findById(8);
        // 更新前
        System.out.println("更新前:" + comment);
        // 修改评论内容
        comment.setContent("这孩子打小就聪明!");
        comment.setAuthor("星辰");
        // 更新评论记录
        int count = commentMapper.updateComment(comment);
        // 判断是否更新成功
        if (count > 0) {
            System.out.println("评论更新成功!");
            System.out.println("更新后:" + commentMapper.findById(8));
        } else {
            System.out.println("评论更新失败!");
        }
    }

    @Test
    public void testDeleteComment() {
        // 删除第8条评论
        int count = commentMapper.deleteComment(8);
        // 判断是否删除成功
        if (count > 0) {
            System.out.println("评论删除成功!");
        } else {
            System.out.println("评论删除失败!");
        }
    }


}

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

1、创建接口 - 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.yc.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、注入文章映射器

在这里插入图片描述

2、创建测试方法testFindArticleById()

在这里插入图片描述

  • 运行测试
    在这里插入图片描述

3、创建测试方法testUpdateArticle()

在这里插入图片描述

  • 运行测试
    在这里插入图片描述

三、课后作业

1、在ArticleMapper里添加方法

	 public List<Article> findAllArticles();
    public int insertArticle(Article article);
    public int deleteArticle(Integer id);

2、在测试类编写测试方法

 public void testFindAllArticles();
    public void testInsertArticle();
    public void testDeleteArticle();
  • 步骤:
    在这里插入图片描述
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值