Spring Boot整合MyBatis

一、数据库准备

1、创建数据库blog

在这里插入图片描述

2、创建文章表

在这里插入图片描述

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、给文章表插入数据

在这里插入图片描述

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

4、创建评论表

在这里插入图片描述

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、给评论表插入数据

在这里插入图片描述


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');

二、项目实现

1、创建项目文件

在这里插入图片描述
在这里插入图片描述

2、创建评论实体类

在这里插入图片描述

package net.zjs.lesson09.bean;

/**
 * 功能:评论实体类
 * 作者:zjs
 * 日期: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、创建文章实体类

在这里插入图片描述

package net.zjs.lesson09.bean;

import java.util.List;

/**
 * 功能:文章实体类
 * 作者:zjs
 * 日期: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 +
                '}';
    }
}

4、编写配置文件

  • 将application.properties更名为application.yaml

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

在这里插入图片描述

#配置数据库
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?
    username: root
    password: 12465

(2)设置数据源类型配置

  • 添加druid依赖
    在这里插入图片描述
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
   

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

在这里插入图片描述

5、使用注解方式整合MyBatis

(1)创建Mapper接口

在这里插入图片描述

package net.zjs.lesson09.mapper;

import net.zjs.lesson09.bean.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 功能:评论映射器接口
 * 作者:zjs
 * 日期: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 upadateComment(Comment comment);

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

(2)在测试类编写测试方法

  • 注入评论映射器

  • 注意:按照以往的去注入会出现误报的情况,添加required=false即可解决误报的情况
    在这里插入图片描述

  • 编写按编号查找记录的测试方法
    在这里插入图片描述

(3)运行测试方法

  • 表示已被废弃
    在这里插入图片描述
  • 修改属性的全局权限
    在这里插入图片描述
  • 再次运行,查看结果
    在这里插入图片描述
  • 修改application.yaml

在这里插入图片描述

  • 再次运行测试方法
    在这里插入图片描述

(4)编写测试方法,查看结果

  • 编写查询全部记录测试方法
    在这里插入图片描述

  • 运行查看结果
    在这里插入图片描述

  • 编写插入记录测试方法
    在这里插入图片描述

  • 运行测试方法

在这里插入图片描述

  • 编写更新记录测试方法

在这里插入图片描述

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

  • 编写删除记录测试方法
    在这里插入图片描述

  • 运行测试方法

  • 在这里插入图片描述

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

(1)创建Mapper接口文件

在这里插入图片描述

package net.zjs.lesson09.mapper;

import net.zjs.lesson09.bean.Article;
import org.apache.ibatis.annotations.Mapper;

/**
 * 功能:文章映射器接口
 * 作者:zjs
 * 日期:2021-05-10
 */
@Mapper
public interface ArticleMapper {
    Article findArticleById(Integer id);
    int updateArticle(Article article);
}

(2)创建映射器配置文件

在这里插入图片描述

<?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.zjs.lesson09.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)在测试类编写测试方法

在这里插入图片描述

  • 按照编号查找

在这里插入图片描述

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

  • 编写更新测试方法
    在这里插入图片描述

  • 运行测试方法

在这里插入图片描述

7、课后练习

(1)编写查询全部记录测试方法

在这里插入图片描述

  • 在mapper.xml文件中 将resultType 和resultMap 混淆

  • 注意:使用resultMap时,必须要有标签指明id和返回类型以及表字段的对应关系。

  • 如果是直接返回一个用户定义的实体类型,则要使用resultType,弄混淆就会报错。

  • 三 resultType 和resultMap的区别
    = resultType:当使用resultType做SQL语句返回结果类型处理时,对于SQL语句查询出的字段在相应的pojo中必须有和它相同的字段对应,而resultType中的内容就是pojo在本项目中的位置。

  • resultMap进行处理对应的。多表连接查询时,若是一对一的连接查询,那么需要新建一个pojo,pojo中包括两个表中需要查询出的所有的字段,这个地方的处理方式通常为创建一个继承一个表字段的pojo,再在里面添加另外一个表内需要查询出的字段即可。若是一对多查询时,若是使用内连接查询,则很可能出现查询出的字段有重复。使用双重for循环嵌套处理即可。

在这里插入图片描述

  • 编写测试方法
    在这里插入图片描述

  • 运行效果
    在这里插入图片描述

(2)编写插入记录的测试方法

在这里插入图片描述

在这里插入图片描述

  • 编写测试方法
    在这里插入图片描述
  • 运行测试方法
    在这里插入图片描述
    在这里插入图片描述

(3)编写删除记录的测试方法

在这里插入图片描述

在这里插入图片描述

  • 编写测试方法

在这里插入图片描述

  • 运行测试方法

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值