在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。
Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。
Spring Boot提供的常见数据库依赖启动器
| 名称 | 对应数据库 | 
|---|---|
| spring-boot-starter-data-jpa | Spring Data JPA, Hibernate | 
| spring-boot-starter-data-mongodb | MongoDB, Spring Data MongoDB | 
| spring-boot-starter-data-neo4j | Neo4j图数据库, Spring Data Neo4j | 
| spring-boot-starter-data-redis | Redis | 
创建数据库、数据表并插入一定的数据
在Navicat的查询里,通过语句创建博客数据库blog
create database blog;

在Navicat里打开刚才创建的博客数据库

在博客数据库里创建文章表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=4 DEFAULT CHARSET=utf8;
在文章表t_article里插入数据记录

INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('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=8 DEFAULT CHARSET=utf8;
在评论表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');
 
查看评论表内容

Spring Initializr模板创建Spring Boot项目 - SpringBootMyBatisDemo

配置项目基本信息

选择Spring Boot版本,添加相关依赖

设置项目名称与保存位置

单击【Finish】按钮

查看pom.xml文件,再添加一个配置处理器依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.12 net.army.boot springbootmybatisdemo 0.0.1-SNAPSHOT SpringBootMyBatisDemo Demo project for Spring Boot 11 org.mybatis.spring.boot mybatis-spring-boot-starter 2.3.1 org.springframework.boot spring-boot-devtools runtime true com.mysql mysql-connector-j runtime org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-maven-plugin 
更新Maven项目依赖

在net.army.boot根包里创建bean子包,在子包里创建Comment类

package net.army.boot.bean;
/**
 * 功能:评论实体类
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */
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


在net.army.boot.bean包里创建Article类

package net.army.boot.bean;
import java.util.List;
/**
 * 功能:文章实体类
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */
public class Article {
    private Integer id;
    private String title;
    private String content;
    private List comments;
    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 getComments() {
        return comments;
    }
    public void setComments(List comments) {
        this.comments = comments;
    }
    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", comments=" + comments +
                '}';
    }
}
    
将全局配置文件application.properties更名为application.yaml


配置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 数据库驱动配置并非必须
这里采用阿里巴巴的Druid数据源
com.alibaba druid-spring-boot-starter 1.2.18 
在pom.xml文件里添加Druid依赖,更新Maven项目依赖

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

在net.army.boot根包里创建mapper子包,在子包里创建CommentMapper接口

package net.army.boot.mapper;
import net.army.boot.bean.Comment;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
 * 功能:评论映射器接口
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */
@Mapper // 交给Spring容器管理
public interface CommentMapper {
    @Insert("insert into t_comment values(#{id}, #{content}, #{author}, #{aId})")
    int insert(Comment comment); // 插入评论记录
    @Delete("delete from t_comment where id = #{id}")
    int deleteById(Integer id); // 按标识符删除评论
    @Update("update t_comment set content = #{content}, author = #{author} where id = #{id}")
    int update(Comment comment); // 更新评论
    @Select("select * from t_comment where id = #{id}")
    Comment findById(Integer id); // 按标识符查询评论
    @Select("select * from t_comment")
    List findAll(); // 查询全部评论
}
  
打开默认的测试类

注入评论映射器

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

有一个警告信息

修改配置文件,可以避免上述警告信息

再运行testFindById()方法,查看结果,已无报红

再次修改配置文件

运行testFindById()方法,查看结果
 将配置文件改回去
将配置文件改回去

修改标识符变量值,再进行测试


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

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

在Navicat里打开评论表,看是否成功地添加了一条新记录

创建testUpdate()方法,修改刚才插入的第7条记录
@Test // 测试更新评论       
public void testUpdate() {                                           
    // 获取标识符为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条记录

创建testDelete()方法,删除刚才插入的第8条记录
@Test // 测试按标识符删除评论                                  
public void testDeleteById() {                       
    // 定义标识符变量                                       
    Integer id = 8;                                  
    // 调用评论映射器实体的删除评论方法                              
    int count = commentMapper.deleteById(id);        
    // 判断评论是否删除成功                                    
    if (count > 0) { // 成功                           
        System.out.println("恭喜,评论删除成功~");            
    } else { // 失败                                   
        System.out.println("遗憾,评论删除失败~");            
    } 
}     
 
运行testDeleteById()方法,查看结果

在Navicat里查看评论表
 再次运行testDeleteById()方法,查看结果
再次运行testDeleteById()方法,查看结果


package net.army.boot.mapper;
import net.army.boot.bean.Article;
/**
 * 功能:文章映射器接口
 * 作者:梁辰兴
 * 日期:2023年06月11日
 */
public interface ArticleMapper {
    Article findArticleById(Integer id);
    int updateArticle(Article article);
}
 
在resources目录里创建mapper目录,在mapper目录里创建ArticleMapper.xml

UPDATE t_article WHERE id = #{id} title = #{title}, content = #{content} 

注入文章映射器

@Test // 测试按照编号查询文章记录                                   
public void testFindArticleById() {                     
    Integer id = 1;                                     
    Article article = articleMapper.findArticleById(id);
    if (article != null) {                              
        System.out.println(article);                    
    } else {                                            
        System.out.println("编号为[" + id + "]的文章未找到!");   
    }    
}       
 
运行testFindArticleById()测试方法,查看结果
@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() 测试方法,查看结果