0


Spring Boot整合MyBatis

文章目录


一、Spring Boot数据访问概述

在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。

Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。

Spring Boot提供的常见数据库依赖启动器
名称对应数据库spring-boot-starter-data-jpaSpring Data JPA, Hibernatespring-boot-starter-data-mongodbMongoDB, Spring Data MongoDBspring-boot-starter-data-neo4jNeo4j图数据库, Spring Data Neo4jspring-boot-starter-data-redisRedis

二、Spring Boot 整合MyBatis

(一)基础环境搭建

1、数据准备

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

(1)创建博客数据库

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

create database 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=4DEFAULT CHARSET=utf8;

(3)文章表插入记录

在文章表t_article里插入数据记录
在这里插入图片描述

INSERT INTO `t_article` VALUES ('1', 'SpringBoot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'SpringCloud基础入门', '从入门到精通讲解...');
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=8DEFAULT 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项目

Spring Initializr模板创建Spring Boot项目 - SpringBootMyBatisDemo
在这里插入图片描述
配置项目基本信息
在这里插入图片描述
选择Spring Boot版本,添加相关依赖
在这里插入图片描述
设置项目名称与保存位置
在这里插入图片描述
单击【Finish】按钮
在这里插入图片描述
查看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.7.12</version><relativePath/><!-- lookup parent from repository --></parent><groupId>net.army.boot</groupId><artifactId>springbootmybatisdemo</artifactId><version>0.0.1-SNAPSHOT</version><name>SpringBootMyBatisDemo</name><description>Demo project forSpringBoot</description><properties><java.version>11</java.version></properties><dependencies><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

更新Maven项目依赖
在这里插入图片描述

(2)创建评论实体类

在net.army.boot根包里创建bean子包,在子包里创建Comment类
在这里插入图片描述

packagenet.army.boot.bean;/**
 * 功能:评论实体类
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */publicclassComment{privateInteger id;privateString content;privateString author;privateInteger aId;publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetContent(){return content;}publicvoidsetContent(String content){this.content = content;}publicStringgetAuthor(){return author;}publicvoidsetAuthor(String author){this.author = author;}publicIntegergetaId(){return aId;}publicvoidsetaId(Integer aId){this.aId = aId;}@OverridepublicStringtoString(){return"Comment{"+"id="+ id +", content='"+ content +'\''+", author='"+ author +'\''+", aId="+ aId +'}';}}

文章编号aId,使用了驼峰命名法,对应表中的a_id字段

全局配置文件中必须配置以下语句,否则查出数据为null
在这里插入图片描述
在这里插入图片描述

(3)创建文章实体类

在net.army.boot.bean包里创建Article类
在这里插入图片描述

packagenet.army.boot.bean;importjava.util.List;/**
 * 功能:文章实体类
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */publicclassArticle{privateInteger id;privateString title;privateString content;privateList<Comment> comments;publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetTitle(){return title;}publicvoidsetTitle(String title){this.title = title;}publicStringgetContent(){return content;}publicvoidsetContent(String content){this.content = content;}publicList<Comment>getComments(){return comments;}publicvoidsetComments(List<Comment> comments){this.comments = comments;}@OverridepublicStringtoString(){return"Article{"+"id="+ id +", title='"+ title +'\''+", content='"+ content +'\''+", comments="+ comments +'}';}}

3、编写配置文件

将全局配置文件application.properties更名为application.yaml
在这里插入图片描述
在这里插入图片描述

(1)配置数据源

配置datasource属性
在这里插入图片描述

# 配置数据源
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

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

(2)配置数据源类型

这里采用阿里巴巴的Druid数据源

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

在pom.xml文件里添加Druid依赖,更新Maven项目依赖
在这里插入图片描述

(3)配置Druid数据源

设置数据源type是Druid数据源

# 配置Druid数据库
    type:com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size:20 # 初始连接数
      min-idle:10 # 最小空闲连接数
      max-active:100 # 最大连接数

设置Druid数据源的一些属性
在这里插入图片描述

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

1、创建评论映射器接口

在net.army.boot根包里创建mapper子包,在子包里创建CommentMapper接口
在这里插入图片描述

packagenet.army.boot.mapper;importnet.army.boot.bean.Comment;importorg.apache.ibatis.annotations.*;importjava.util.List;/**
 * 功能:评论映射器接口
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */@Mapper// 交给Spring容器管理publicinterfaceCommentMapper{@Insert("insert into t_comment values(#{id}, #{content}, #{author}, #{aId})")intinsert(Comment comment);// 插入评论记录@Delete("delete from t_comment where id = #{id}")intdeleteById(Integer id);// 按标识符删除评论@Update("update t_comment set content = #{content}, author = #{author} where id = #{id}")intupdate(Comment comment);// 更新评论@Select("select * from t_comment where id = #{id}")CommentfindById(Integer id);// 按标识符查询评论@Select("select * from t_comment")List<Comment>findAll();// 查询全部评论}

2、测试评论映射器接口

打开默认的测试类
在这里插入图片描述
注入评论映射器
在这里插入图片描述

(1)测试按标识符查询评论方法

创建testFindById()方法

@Test// 测试按标识符查询评论                                               publicvoidtestFindById(){// 定义标识符变量                                                    Integer id =1;// 调用评论映射器实体的按标识符查询评论方法                                       Comment comment = commentMapper.findById(id);// 判断查询是否成功                                                   if(comment !=null){// 成功                                  System.out.println(comment);}else{// 失败                                                System.out.println("标识符为["+ id +"]的评论未找到~");}}

运行testFindById()方法,查看结果
在这里插入图片描述
有一个警告信息
在这里插入图片描述
修改配置文件,可以避免上述警告信息
在这里插入图片描述
再运行testFindById()方法,查看结果,已无报红
在这里插入图片描述
再次修改配置文件
在这里插入图片描述
运行testFindById()方法,查看结果
在这里插入图片描述将配置文件改回去
在这里插入图片描述
修改标识符变量值,再进行测试
在这里插入图片描述在这里插入图片描述

(2)测试查询全部评论方法

创建testFindAll()方法

@Test// 测试查询全部评论                                                       publicvoidtestFindAll(){// 调用评论映射器实体的查询全部评论方法                                               List<Comment> comments = commentMapper.findAll();// 判断是否有评论                                                          if(!comments.isEmpty()){// 有评论                                   
        comments.forEach(comment ->System.out.println(comment));}else{// 没有评论                                                    System.out.println("温馨提示:评论表里没有记录~");}}

运行testFindAll()方法,查看结果
在这里插入图片描述

(3)测试插入评论方法

创建testInsert()方法

@Test// 测试插入评论                                       publicvoidtestInsert(){// 创建评论对象                                         Comment comment =newComment();// 设置评论对象属性                                       
    comment.setContent("写得很有用,赞一个~");                 
    comment.setAuthor("梁辰兴");                         
    comment.setaId(2);// 调用评论映射器实体的插入评论方法                                 int count = commentMapper.insert(comment);// 判断评论是否插入成功                                     if(count >0){// 成功                            System.out.println("恭喜,评论插入成功~");}else{// 失败                                    System.out.println("遗憾,评论插入失败~");}}

运行testInsert()方法,查看结果
在这里插入图片描述
在Navicat里打开评论表,看是否成功地添加了一条新记录

在这里插入图片描述

(4)测试更新评论方法

创建testUpdate()方法,修改刚才插入的第7条记录

@Test// 测试更新评论                                                      publicvoidtestUpdate(){// 获取标识符为7的评论对象                                                  Comment comment = commentMapper.findById(7);// 输出更新前的评论对象                                                    System.out.println("更新前:"+ comment);// 修改评论对象                                                        
    comment.setContent("简单明了,讲解清晰,适合初学者~");                          
    comment.setAuthor("梁辰兴");// 调用评论映射器实体的更新评论方法                                              int count = commentMapper.update(comment);// 判断评论是否更新成功                                                    if(count >0){// 成功                                           System.out.println("恭喜,评论更新成功~");System.out.println("更新后:"+ commentMapper.findById(7));}else{// 失败                                                   System.out.println("遗憾,评论更新失败~");}}

运行testUpdate()方法,查看结果
在这里插入图片描述
在Navicat里查看评论表第7条记录
在这里插入图片描述

(5)测试删除评论方法

创建testDelete()方法,删除刚才插入的第8条记录

@Test// 测试按标识符删除评论                                  publicvoidtestDeleteById(){// 定义标识符变量                                       Integer id =8;// 调用评论映射器实体的删除评论方法                              int count = commentMapper.deleteById(id);// 判断评论是否删除成功                                    if(count >0){// 成功                           System.out.println("恭喜,评论删除成功~");}else{// 失败                                   System.out.println("遗憾,评论删除失败~");}}

运行testDeleteById()方法,查看结果
在这里插入图片描述
在Navicat里查看评论表
在这里插入图片描述再次运行testDeleteById()方法,查看结果
在这里插入图片描述

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

1、创建文章映射接口 - ArticleMapper

在这里插入图片描述

packagenet.army.boot.mapper;importnet.army.boot.bean.Article;/**
 * 功能:文章映射器接口
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */publicinterfaceArticleMapper{ArticlefindArticleById(Integer id);intupdateArticle(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.army.boot.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()

@Test// 测试按照编号查询文章记录                                   publicvoidtestFindArticleById(){Integer id =1;Article article = articleMapper.findArticleById(id);if(article !=null){System.out.println(article);}else{System.out.println("编号为["+ id +"]的文章未找到!");}}

运行testFindArticleById()测试方法,查看结果

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

@Test                                                                 
public void testUpdateArticle(){                                     
    Article article = articleMapper.findArticleById(1);               
    System.out.println("更新前:"+ article);                             
    article.setContent("一步步接近企业真实项目~");int count = articleMapper.updateArticle(article);// 判断是否更相信成功                                                      
    if(count >0){                                                  
        System.out.println("文章更新成功!");                                
        System.out.println("更新后:"+ articleMapper.findArticleById(1));}else{                                                          
        System.out.println("文章更新失败!");}}

运行testUpdateArticle() 测试方法,查看结果

三、练习

1、在ArticleMapper里添加方法

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


本文转载自: https://blog.csdn.net/m0_62617719/article/details/131151130
版权归原作者 梁辰兴 所有, 如有侵权,请联系我们删除。

“Spring Boot整合MyBatis”的评论:

还没有评论