一.用户相关数据库操作
- 根据用户名,查询用户信息
- 根据用户id,查询用户信息
package com.example.demo.mapper;
import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserInfoMapper {
/**
* 根据用户名, 查询用户信息
* @return
*/
@Select("select * from user where delete_flag =0 and user_name = #{userName}")
UserInfo selectByName(String userName);
/**
* 根据用户ID, 查询用户信息
* @return
*/
@Select("select * from user where delete_flag =0 and id = #{id}")
UserInfo selectById(Integer id);
}
代码解读:
这段代码使用MyBatis注解方式定义了一个名为UserInfoMapper
的接口,该接口包含两个方法:selectByName
和selectById
,分别用于根据用户名和用户ID从数据库中查询用户信息,并返回UserInfo
对象。
单元测试:
package com.example.demo.mapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserInfoMapperTest {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
void selectByName() {
System.out.println(userInfoMapper.selectByName("zhangsan"));
}
@Test
void selectById() {
System.out.println(userInfoMapper.selectById(2));
}
}
代码解读:用于测试UserInfoMapper
接口中的selectByName
和selectById
方法,通过自动注入UserInfoMapper
实例并调用其方法来验证数据库查询功能的正确性,测试结果通过控制台输出显示。
二.博客相关数据库操作
- 查询博客列表
- 根据博客ID,返回作者信息
- 根据博客ID,返回博客详情
- 根据用户输入的信息,更新博客
- 根据博客ID,删除博客
- 根据用户输入的信息,添加博客
package com.example.demo.mapper;
import com.example.demo.model.BlogInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface BlogMapper {
/**
* 返回博客列表
* @return
*/
@Select("select * from blog where delete_flag = 0")
List<BlogInfo> selectAll();
/**
* 根据博客ID, 返回博客信息
* @return
*/
@Select("select * from blog where id =#{id}")
BlogInfo selectById(Integer id);
/**
* 更新博客
* @return
*/
Integer updateBlog(BlogInfo blogInfo);
/**
* 发布博客
*/
@Insert("insert into blog (title, content, user_id) values (#{title}, #{content}, #{userId})")
Integer insertBlog(BlogInfo blogInfo);
}
代码解读:
BlogMapper
接口是一个MyBatis Mapper接口,用于定义与博客数据表(blog)交互的SQL语句,包括查询博客列表、根据博客ID查询博客信息、更新博客以及发布新博客的操作。通过注解方式直接在接口方法上编写SQL语句
注意事项:更新博客操作,在xml文件配置(sql语句较长)
<?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="com.bite.blog.mapper.BlogMapper">
<update id="updateBlog">
update blog
<set>
<if test="title!=null">
title = #{title},
</if>
<if test="content!=null">
content = #{content},
</if>
<if test="userId!=null">
user_id = #{userId},
</if>
<if test="deleteFlag!=null">
delete_flag = #{deleteFlag},
</if>
</set>
where id = #{id}
</update>
</mapper>
xml文件的使用:
想象一下,你有一个博客系统,里面有很多博客文章。这些文章存储在数据库的一个叫做blog
的表中。现在,你想要更新这些文章中的某些信息,比如标题、内容、作者ID或者一个标记是否这篇文章应该被删除(delete_flag
)。但是,你可能只想更新其中一些信息,而不是每次都更新全部。
这个XML文件就是用来告诉MyBatis怎么做这件事的。它定义了一个“规则”,这个规则告诉MyBatis:“嘿,当你想要更新blog
表里的文章时,就按照这个模板来构建SQL语句吧。”
在这个“规则”里,有一个叫做updateBlog
的部分。它说:“首先,找到blog
表。然后,根据传进来的信息(比如文章的新标题、新内容、新的作者ID,或者新的删除标记),如果这些信息不是空的,就更新对应的字段。但是,不管更新哪些字段,都只更新ID匹配的那篇文章。”
这里用到了<if>
这样的“智能”标签,它们就像是小小的决策者。它们会检查你传进来的文章信息(比如标题、内容等)是不是空的。如果不空,它们就会说:“哦,这个字段有值,我们应该在SQL语句里包含它。”
最后,<set>
标签就像是一个聪明的组织者,它会确保所有的字段更新语句都被正确地组织在一起,并且在每个字段更新语句的末尾(除了最后一个)都加上逗号,但是在最后一个字段后面不加逗号,以防SQL语句出错。
总的来说,这个XML文件就是一个“模板”,它告诉MyBatis如何根据你的需求动态地构建出正确的SQL更新语句,来更新blog
表中的文章。
单元测试:
原始数据库
日志展示:
数据库展示:
三.实现博客列表接口
3.1BlogController类
package com.example.demo.controller;
import com.example.demo.model.BlogInfo;
import com.example.demo.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
@Autowired
private BlogService blogService;
@RequestMapping(value = "/getList")
public List<BlogInfo> getList(){
log.info("获取博客列表..");
return blogService.getList();
}
@RequestMapping("/getBlogDetail")
public BlogInfo getBlogDetail(Integer blogId){
log.info("getBlogDetail, blogId: {}", blogId);
return blogService.getBlogDetail(blogId);
}
}
3.2BlogService类
package com.example.demo.service;
import com.example.demo.mapper.BlogMapper;
import com.example.demo.model.BlogInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BlogService {
@Autowired
private BlogMapper blogMapper;
public List<BlogInfo> getList() {
return blogMapper.selectAll();
}
public BlogInfo getBlogDetail(Integer blogId) {
return blogMapper.selectById(blogId);
}
}
3.3UserService类
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
}
3.4postman测试接口
四.编写展示博客列表前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>博客列表页</title>
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/list.css">
</head>
<body>
<div class="nav">
<img src="pic/logo2.jpg" alt="">
<span class="blog-title">我的博客系统</span>
<div class="space"></div>
<a class="nav-span" href="blog_list.html">主页</a>
<a class="nav-span" href="blog_edit.html">写博客</a>
<a class="nav-span" href="#" onclick="logout()">注销</a>
</div>
<div class="container">
<div class="left">
<div class="card">
<img src="pic/doge.jpg" alt="">
<h3>比特汤老师</h3>
<a href="#">GitHub 地址</a>
<div class="row">
<span>文章</span>
<span>分类</span>
</div>
<div class="row">
<span>2</span>
<span>1</span>
</div>
</div>
</div>
<div class="right">
<!--<div class="blog">
<div class="title">我的第一篇博客</div>
<div class="date">2021-06-02</div>
<div class="desc">今天开始, 好好学习Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quas nesciunt, hic voluptatum, dolorem quisquam modi accusantium, commodi dolores architecto ratione vel exercitationem optio. Facere repellendus autem, obcaecati dolore sequi incidunt?</div>
<a class="detail" href="blog_detail.html">查看全文>></a>
</div>
<div class="blog">
<div class="title">我的第一篇博客</div>
<div class="date">2021-06-02</div>
<div class="desc">今天开始, 好好学习Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quas nesciunt, hic voluptatum, dolorem quisquam modi accusantium, commodi dolores architecto ratione vel exercitationem optio. Facere repellendus autem, obcaecati dolore sequi incidunt?</div>
<a class="detail" href="blog_detail.html">查看全文>></a>
</div>-->
</div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$.ajax({
type: "get",
url: "/blog/getList",
success: function(result){
if(result.code=="SUCCESS"){
var blogs = result.data;
var finalHtml = "";
for(var blog of blogs){
finalHtml +='<div class="blog">';
finalHtml +='<div class="title">'+blog.title+'</div>';
finalHtml +='<div class="date">'+blog.createTime+'</div>';
finalHtml +='<div class="desc">'+blog.content+'</div>';
finalHtml +='<a class="detail" href="blog_detail.html?blogId='+blog.id+'">查看全文>></a>';
finalHtml +='</div>';
}
$(".container .right").html(finalHtml);
}
}
});
</script>
<script src="js/common.js"></script>
</body>
</html>
展示: