1.创建数据库【blog】
创建表【t_article】【t_comment】
CREATE DATABASE blog;
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;
INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('3', '安卓开发权威指南', '从入门到精通讲解...');
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;
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.新建一个项目[MybatisDemo]
引入MySQL和MyBatis的依赖启动器
(1)创建评论实体类 - Comment。
package net.qyk.lesson06.bean;
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 +
'}';
}
}
(2)创建文章实体类 - Article
package net.qyk.lesson06.bean;
import java.util.List;
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、编写配置文件
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
type: com.alibaba.druid.pool.DruidDataSource
druid.initial-size: 20
druid.min-idle: 10
druid.max-active: 100
mybatis:
configuration:
map-underscore-to-camel-case: true
(1)在pom.xml文件里添加druid依赖
<?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.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.qyk.lesson06</groupId>
<artifactId>mybatisdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MybatisDemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(二)使用注解方式整合MyBatis
1、创建评论映射器接口 - CommentMapper
package net.qyk.lesson06.mapper;
import net.qyk.lesson06.bean.Comment;
import org.apache.ibatis.annotations.*;
import java.util.List;
@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 updateComment(Comment comment);
// 删除记录
@Delete("delete from t_comment where id = #{id}")
int deleteComment(Integer id);
}
2、在测试类编写测试方法
package net.qyk.lesson06;
import net.qyk.lesson06.bean.Comment;
import net.qyk.lesson06.mapper.CommentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MybatisDemoApplicationTests {
@Autowired(required = false)
private CommentMapper commentMapper;
@Test
void contextLoads() {
Comment comment = commentMapper.findById(1);
if (comment != null) {
System.out.println(comment);
} else {
System.out.println("评论未找到");
}
}
}
测试结果
package net.qyk.lesson06;
import net.qyk.lesson06.bean.Article;
import net.qyk.lesson06.bean.Comment;
import net.qyk.lesson06.mapper.ArticleMapper;
import net.qyk.lesson06.mapper.CommentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MybatisDemoApplicationTests {
@Autowired(required = false)
private CommentMapper commentMapper;
@Autowired(required = false)
private ArticleMapper articleMapper;
@Test
void contextLoads() {
Comment comment = commentMapper.findById(1);
if (comment != null) {
System.out.println(comment);
} else {
System.out.println("评论未找到");
}
}
@Test
public void testFindAll() {
List<Comment> comments = commentMapper.findAll();
for (Comment comment : comments) {
System.out.println(comment);
}
}
@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("遗憾,评论添加失败!");
}
}
@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("遗憾,评论更新失败!");
}
}
@Test
public void testDeleteComment() {
// 删除第8条评论
int count = commentMapper.deleteComment(8);
// 判断是否删除成功
if (count > 0) {
System.out.println("恭喜,评论删除成功!");
} else {
System.out.println("遗憾,评论删除失败!");
}
}
@Test
public void testFindArticleById() {
Article article = articleMapper.findArticleById(1);
if (article != null) {
System.out.println(article);
} else {
System.out.println("文章未找到!");
}
}
@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("遗憾,文章更新失败!");
}
}
}