文章目录
零、学习目标
1、了解Spring Boot数据访问概述
2、掌握使用注解的方式整合MyBatis
3、掌握使用配置文件的方式整合MyBatis
一、Spring Boot数据访问概述
- 在开发中,通常会涉及到对数据库的数据进行操作,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 |
二、Spring Boot 整合MyBatis
(一)基础环境搭建
1、数据准备
- 创建数据库、数据表并插入一定的数据
(1)创建博客数据库blog
- 在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=3 DEFAULT CHARSET=utf8;
(3)在文章表t_article里插入数据记录
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
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=7 DEFAULT 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项目MyBatisDemo
- 引入MySQL和MyBatis的依赖启动器
- 设置项目名称与保存位置
- 完成项目初始化工作
(2)创建评论实体类Comment
package net.hw.lesson06;
/**
* 功能:评论实体类
* 作者:华卫
* 日期:2020年08月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
mybatis.configuration.map-underscore-to-camel-case=true
(3)创建文章实体类Article
package net.hw.lesson06;
import java.util.List;
/**
* 功能:文章实体类
* 作者:华卫
* 日期:2020年08月11日
*/
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)在全局配置文件中进行数据库连接配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/blog?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
扫描二维码关注公众号,回复:
11632047 查看本文章
![](/qrcode.jpg)
- 说明:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
数据库驱动配置并非必须
(2)设置数据源类型配置(以阿里巴巴的Druid数据源为例)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
(3)在全局配置文件里覆盖默认参数
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始连接数
spring.datasource.druid.initial-size=20
#最小空闲数
spring.datasource.druid.min-idle=10
#最大连接数
spring.datasource.druid.max-active=100
(二)使用注解方式整合MyBatis
1、创建Mapper接口CommentMapper
package net.hw.lesson06;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* 功能:评论映射器接口
* 作者:华卫
* 日期:2020年08月11日
*/
@Mapper // 由Spring管理的MyBatis接口
public interface CommentMapper {
// 按编号查询记录
@Select("select * from t_comment where id = #{id}")
public Comment findById(Integer id);
// 查找全部记录
@Select("select * from t_comment")
public List<Comment> findAll();
// 插入记录
@Insert("insert into t_comment values(#{id}, #{content}, #{author}, #{aId})")
public int insertComment(Comment comment);
// 更新记录
@Update("update t_comment set content = #{content}, author = #{author} where id = #{id}")
public int updateComment(Comment comment);
// 删除记录
@Delete("delete from t_comment where id = #{id}")
public int deleteComment(Integer id);
}
2、在测试类编写测试方法
- 注入评论映射器
(1)创建测试方法testFindById()
@Test
public void testFindById() {
Comment comment = commentMapper.findById(1);
System.out.println(comment.toString());
}
- 运行测试方法,查看结果
- 测试通过,但是输出结果有个小问题,文章编号
aId
的值为null
。为什么呢?因为aId
属性对应的是评论表中的a_id
字段,需要在全局配置文件里对MyBatis进行一个转换配置:mybatis.configuration.map-underscore-to-camel-case=true
- 再运行测试方法,查看结果
- 大家可以看到,文章编号
aId
属性的值输出来了。
(2)创建测试方法testFindAll()
@Test
public void testFindAll() {
List<Comment> comments = commentMapper.findAll();
for (Comment comment : comments) {
System.out.println(comment);
}
}
- 运行测试方法,查看结果
(3)创建测试方法testInsertComment()
@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("遗憾,评论添加失败!");
}
}
- 运行测试方法,查看结果
- 在Navicat里打开评论表,看是否成功地添加了一条新记录
(4)创建测试方法testUpdateComment()
- 修改刚才插入的第8条记录
@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("遗憾,评论更新失败!");
}
}
- 运行测试方法,查看结果
(5)创建测试方法testDeleteComment()
- 删除刚才插入的第8条记录
@Test
public void testDeleteComment() {
// 删除第8条评论
int count = commentMapper.deleteComment(8);
// 判断是否删除成功
if (count > 0) {
System.out.println("恭喜,评论删除成功!");
} else {
System.out.println("遗憾,评论删除失败!");
}
}
- 运行测试方法,查看结果
- 在Navicat里查看评论表t_comment
(三)使用配置文件方式整合MyBatis
1、创建Mapper接口文件 - ArticleMapper
package net.hw.lesson06;
import org.apache.ibatis.annotations.Mapper;
/**
* 功能:文章映射器接口
* 作者:华卫
* 日期:2020年08月11日
*/
@Mapper
public interface ArticleMapper {
public Article findArticleById(Integer id);
public int updateArticle(Article article);
}
2、创建XML映射文件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.hw.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>
重构:将不同类型的文件放在不同的包里
(1)新建bean子包,存放实体类
(2)新建mapper子包,保存映射器接口
3、在全局配置文件里配置XML映射文件路径
#配置MyBatis的xml配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置XML映射文件中指定的实体类别名路径
mybatis.type-aliases-package=net.hw.lesson06.bean
4、在测试类编写测试方法
- 注入文章映射器
(1)创建测试方法testFindArticleById()
@Test
public void testFindArticleById() {
Article article = articleMapper.findArticleById(1);
System.out.println(article);
}
- 运行测试方法,查看结果
(2)创建测试方法testUpdateArticle()
@Test
public void testUpdateArticle() {
// 获取第1篇文章
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("遗憾,文章更新失败!");
}
}
- 运行测试方法,查看结果
三、课后作业
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();