文章目录

  • 一、正文
  • Spring Boot 数据访问
  • 1、基础环境搭建
  • - 数据准备
  • - 创建项目(MybatisDemo1)
  • - 创建评论实体类
  • - 创建文章实体类
  • - 编写全局配置文件
  • 2、使用注解方式整合MyBatis
  • - 创建评论映射器接口
  • - 在测试类编写测试方法
  • 1)testFindById()
  • 2)testFindAll()
  • 3)testInsertComment()
  • 4) testUpdateComment()
  • 5) testDeleteComment()
  • 3、使用配置文件方式整合MyBatis
  • - 创建文章映射器接口
  • - 创建映射器配置文件
  • - 全局配置文件里配置映射器配置文件路径
  • - 在测试类编写测试方法
  • 1)testFindArticleById()
  • 2)testUpdateArticle()
  • 3 ) testFindAllArticles()
  • 4 ) testInsertArticle()
  • 5 ) testDeleteArticle()
  • 二、总结


一、正文

Spring Boot 数据访问

  • 访问关系数据库

1、基础环境搭建

- 数据准备

  • 数据库-blog

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试

  • 文章表
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;

SpringBoot项目中版本在哪里看 springboot版本对应_System_02

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

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_03

  • 评论表
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;

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_04

  • 评论表插入数据
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');

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_05

- 创建项目(MybatisDemo1)

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_06

  • 引入MySQL和MyBatis的依赖启动器

SpringBoot项目中版本在哪里看 springboot版本对应_SpringBoot项目中版本在哪里看_07

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_08

- 创建评论实体类

SpringBoot项目中版本在哪里看 springboot版本对应_System_09

package net.zy.lesson06.bean;

// 2021.5.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 +
                '}';
    }
}

- 创建文章实体类

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_10

package net.zy.lesson06.bean;

import java.util.List;

//2021.5.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 +
                '}';
    }
}

- 编写全局配置文件

  • 数据库连接配置
# 配置数据库
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: root
  • 数据源配置

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_11

  • 覆盖默认参数

SpringBoot项目中版本在哪里看 springboot版本对应_System_12

2、使用注解方式整合MyBatis

- 创建评论映射器接口

  • CommentMapper.java
package net.zy.lesson06.mapper;


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

import java.util.List;

//2021.5.10   评论映射器接口 

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


}

- 在测试类编写测试方法

  • MybatisDemo1ApplicationTests
  • 注入评论映射器

SpringBoot项目中版本在哪里看 springboot版本对应_SpringBoot项目中版本在哪里看_13

1)testFindById()
  • 按编号查询记录
@Test
    public void testFindById(){
       Integer id = 1;
        Comment comment = commentMapper.findById(1);
        if (comment != null) {
            System.out.println(comment);
        } else {
            System.out.println("编号为[" + id + "]评论未找到");
        }

    }
  • 运行测试结果报错,则修改一下全局属性配置文件

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_14

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_15

  • aId属性值更新显示

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_16

  • 重新运行,aId值显示了

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_17

2)testFindAll()
  • 查询全部记录
  • SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_18

  • 运行测试方法

SpringBoot项目中版本在哪里看 springboot版本对应_SpringBoot项目中版本在哪里看_19

3)testInsertComment()
  • 插入记录
  • SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_20

  • 运行测试方法

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_21

4) testUpdateComment()
  • 更新记录
@Test
public  void testUpdateComment(){
    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("遗憾,评论更新失败~");
    }
  • 运行测试结果

SpringBoot项目中版本在哪里看 springboot版本对应_SpringBoot项目中版本在哪里看_22

5) testDeleteComment()
  • 删除记录
@Test
    public void testDeleteComment(){
        int count = commentMapper.deleteComment(8);
        if (count > 0){
            System.out.println("恭喜,评论删除成功~");
        }else {
            System.out.println("遗憾,评论删除失败~");
        }
    }
  • 运行测试结果

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

- 创建文章映射器接口

  • ArticleMapper.java
package net.zy.lesson06.mapper;


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

// 2021.5.10  文章映射器接口
@Mapper
public interface ArticleMapper {
    Article findArticleById(Integer id);
    int updateArticle(Article article);

}

- 创建映射器配置文件

  • 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.zy.lesson06.mapper.ArticleMapper">
<!--    两表关联,根据id查询记录-->
    <select id="findArticleById" resultMap="articleWithComment">
        SELECT a.*,  c_id, c.content c_content, c.author, c.a_id
            FROM t_article a, t_comment c
            WHERE  = c.a_id AND  = #{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>

- 全局配置文件里配置映射器配置文件路径

SpringBoot项目中版本在哪里看 springboot版本对应_SpringBoot项目中版本在哪里看_23

- 在测试类编写测试方法

  • MybatisDemo1ApplicationTests
  • 注入文章映射器接口

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_24

1)testFindArticleById()
  • 按编号查询文章记录
@Test
    public void testFindArticleById(){
        Integer id = 1;
        Article article = articleMapper.findArticleById(id);
        if (article != null) {
            System.out.println(article);
        } else {
            System.out.println("编号为[" + id + "]的文章未找到");
        }
    }
  • 运行测试方法
2)testUpdateArticle()
  • 更新文章记录
@Test
    public void testUpdateArticle(){
        Article article = articleMapper.findArticleById(1);
        System.out.println("更新前: " + article);
        article.setContent("带你一步一步接近企业真实项目~");  // 修改评论内容
        article.setContent("咸鱼");
        //更新评论记录
        int count = articleMapper.updateArticle(article);
        if (count > 0){
            System.out.println("恭喜,文章更新成功~");
            System.out.println("更新后:" + articleMapper.findArticleById(1));
        }else {
            System.out.println("遗憾,文章更新失败~");
        }
    }
  • 运行测试方法

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_25

3 ) testFindAllArticles()
  • 查找全部记录
  • ArticleMapper.java里添加方法

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_26

  • ArticleMapper.xml里添加映射语句
    注意 添加了resultMap,一定使用resultMap=“articleWithComment”

SpringBoot项目中版本在哪里看 springboot版本对应_SpringBoot项目中版本在哪里看_27

<select id="findAllArticles" resultMap="articleWithComment">
        SELECT * FROM t_article;
    </select>
  • 编写测试方法
@Test
    public void testFindAllArticles(){
        List<Article> articles = articleMapper.findAllArticles();
        for (Article article : articles){
            System.out.println(article);
        }
    }
  • 运行测试方法

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_28

4 ) testInsertArticle()
  • 插入记录
  • ArticleMapper.java里添加方法
  • SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_29

  • ArticleMapper.xml里添加映射语句
<insert id="insertArticle" parameterType="Article">
        INSERT INTO t_article
        VALUES(#{id},#{title},#{content});
    </insert>
  • 编写测试方法
@Test
    public void testInsertArticle(){
        Article article = new Article();
        article.setId(4);
        article.setTitle("Java 入门");
        article.setContent("从入门到精通...");

        // 插入记录
        int count = articleMapper.insertArticle(article);
        if (count > 0){
            System.out.println("恭喜,文章添加成功~");
        }else {
            System.out.println("遗憾,文章添加失败~");
        }
    }
  • 运行测试方法

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_30

5 ) testDeleteArticle()
  • 删除记录
  • ArticleMapper.java里添加方法

SpringBoot项目中版本在哪里看 springboot版本对应_运行测试_31

  • ArticleMapper.xml里添加映射语句
<delete id="deleteArticle" parameterType="int">
        DELETE FROM t_article WHERE id = #{id};
    </delete>
  • 编写测试方法
@Test
    public void testDeleteArticle(){
        int count = articleMapper.deleteArticle(4);
        if (count > 0){
            System.out.println("恭喜,文章删除成功~");
        }else {
            System.out.println("遗憾,文章删除失败~");
        }
    }
  • 运行测试方法

二、总结

  • 评论映射器接口使用注解方式整合MyBatis ☟

SpringBoot项目中版本在哪里看 springboot版本对应_System_32

  • 文章映射器接口使用配置文件方式整合MyBatis ☟

SpringBoot项目中版本在哪里看 springboot版本对应_System_33


+

SpringBoot项目中版本在哪里看 springboot版本对应_配置文件_34