标签:Blog SpringBoot 博客 blog v1.0 springframework import org id
实现博客分页查询、新增、修改、删除
一、创建持久层(Dao层)
创建接口 BlogRepository 继承 JpaRepository
package com.example.dao;
import com.example.po.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface BlogRepository extends JpaRepository<Blog,Long> {
Page<Blog> findAll(Specification<Blog> blogSpecification, Pageable pageable);
@Query("select b from Blog b where b.recommend = true ")
List<Blog> findTop(Pageable pageable);
@Query("select b from Blog b where b.title like ?1 or b.content like ?1")
Page<Blog> findByQuery(String query,Pageable pageable);
@Modifying
@Query("update Blog b set b.views=b.views+1 where b.id= ?1")
int updateViews(Long id);
}
二、创建service层
1.定义博客业务层接口
创建博客接口 BlogService,定义博客相关的方法
代码如下:
package com.example.service;
import com.example.po.Blog;
import com.example.vo.BlogQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
public interface BlogService {
// 根据id查询blog
Blog getBlog(Long id);
//转换为markdown语法输出
Blog getAndConvert(Long id);
//分页查询 blog查询条件
Page<Blog> listBlog(Pageable pageable, BlogQuery blog);
Page<Blog> listBlog(Pageable pageable);
//根据查询跳转页面
Page<Blog> listBlog(String query, Pageable pageable);
List<Blog> listRecommendBlogTop(Integer size);
//新增
Blog saveBlog(Blog blog);
//更新博客
Blog updateBlog(Long id,Blog blog);
void deleteBlog(Long id);
}
2.创建接口的实现类
创建 BlogServiceImpl实现 用户接口 BlogService
代码如下:
package com.example.service.impl;
import com.example.NotFoundException;
import com.example.dao.BlogRepository;
import com.example.po.Blog;
import com.example.po.Type;
import com.example.service.BlogService;
import com.example.util.MarkdownUtils;
import com.example.util.MyBeanUtils;
import com.example.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class BlogServiceImpl implements BlogService {
@Autowired
private BlogRepository blogRepository;
@Override
public Blog getBlog(Long id) {
return blogRepository.findById(id).orElse(null);
}
@Transactional
@Override
public Blog getAndConvert(Long id) {
Blog blog = blogRepository.findById(id).orElse(null);
if (blog == null){
throw new NotFoundException("该博客不存在");
}
//浏览次数增加
blogRepository.updateViews(id);
//不操做数据库 只进行转换
Blog b= new Blog();
BeanUtils.copyProperties(blog,b);
String content = b.getContent();
b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
return b;
}
@Override
public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
return blogRepository.findAll(new Specification<Blog>() {
@Override
public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>();
if (!"".equals(blog.getTitle()) && blog.getTitle() != null) {
predicates.add(cb.like(root.<String>get("title"), "%"+blog.getTitle()+"%"));
}
if (blog.getTypeId() != null) {
predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
}
if (blog.isRecommend()) {
predicates.add(cb.equal(root.<Boolean>get("recommend"), blog.isRecommend()));
}
cq.where(predicates.toArray(new Predicate[predicates.size()]));
return null;
}
},pageable);
}
@Override
public Page<Blog> listBlog(Pageable pageable) {
return blogRepository.findAll(pageable);
}
@Override
public Page<Blog> listBlog(String query, Pageable pageable) {
return blogRepository.findByQuery(query,pageable);
}
@Override
public List<Blog> listRecommendBlogTop(Integer size) {
// 设置排序对象
Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
Pageable pageable = PageRequest.of(0, size, sort);
return blogRepository.findTop(pageable);
}
@Transactional
@Override
public Blog saveBlog(Blog blog) {
blog.setCreateTime(new Date()); //添加日期
blog.setUpdateTime(new Date());
blog.setViews(0);
return blogRepository.save(blog);
}
@Transactional
@Override
public Blog updateBlog(Long id, Blog blog) { //本质还是执行 saveBlog操作
Blog b = blogRepository.findById(id).orElse(null);
if (b == null){
throw new NotFoundException("该博客不存在");
}
BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));//前面赋值给后面 解决使用save方法的问题,在save更新的时候,发生改变的会更新,没发生改变的会置为空。
System.out.println(blog);
b.setUpdateTime(new Date());
System.out.println(b);
return blogRepository.save(b);
}
@Transactional
@Override
public void deleteBlog(Long id) {
blogRepository.deleteById(id);
}
}
三、博客控制器
创建 BlogController 博客控制器,在这里实现分页查询、添加、保存、修改分类、删除功能,代码如下:
package com.example.web.admin;
import com.example.po.Blog;
import com.example.po.User;
import com.example.service.BlogService;
import com.example.service.TagService;
import com.example.service.TypeService;
import com.example.vo.BlogQuery;
import jdk.internal.util.xml.impl.Input;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/admin")
public class BlogController {
private static final String INPUT = "admin/blogs-input";
private static final String LIST = "admin/blogs";
private static final String REDIRECT_LIST = "redirect:/admin/blogs";
@Autowired
private BlogService blogService;
@Autowired
private TypeService typeService;
@Autowired
private TagService tagService;
/**
* 显示博客列表
* @param pageable
* @param blog
* @param model
* @return
*/
@GetMapping("/blogs")
public String list(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC) //设置pageable 设置排序方式
Pageable pageable, BlogQuery blog, Model model){
model.addAttribute("types",typeService.listType()); //获取所有分类
model.addAttribute("page", blogService.listBlog(pageable, blog));
return LIST;
}
/**
* 显示搜索博客的数据 (只显示搜索部分)
* @param pageable
* @param blog
* @param model
* @return
*/
@PostMapping("/blogs/search")
public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC) //设置pageable 设置排序方式
Pageable pageable, BlogQuery blog, Model model){
model.addAttribute("page", blogService.listBlog(pageable, blog));
return "admin/blogs :: blogList"; //返回blogList片段
}
/**
* 跳转新增页面
* @param model
* @return
*/
@GetMapping("/blogs/input")
public String input(Model model){
setTypeAndTag(model);
model.addAttribute("blog",new Blog());
return INPUT;
}
/**
* 跳转修改页面
* @param model
* @return
*/
@GetMapping("/blogs/{id}/input")
public String editInput(@PathVariable Long id,Model model){
setTypeAndTag(model);
Blog blog = blogService.getBlog(id);
blog.init(); //将blog初始化一个字符串
model.addAttribute("blog",blog);
return INPUT;
}
private void setTypeAndTag(Model model) {
model.addAttribute("types", typeService.listType());
model.addAttribute("tags", tagService.listTag());
}
/**
* 新增博客请求
* @param blog
* @param attributes
* @param session
* @return
*/
@PostMapping("/blogs")
public String post(Blog blog, RedirectAttributes attributes, HttpSession session) {
blog.setUser((User) session.getAttribute("user")); //设置创建博客的对象
blog.setType(typeService.getType(blog.getType().getId()));
blog.setTags(tagService.listTag(blog.getTagIds()));
Blog b;
if (blog.getId() == null) {
b = blogService.saveBlog(blog); //新增博客
} else {
b = blogService.updateBlog(blog.getId(), blog); //修改博客
}
if (b == null ) {
attributes.addFlashAttribute("message", "操作失败");
} else {
attributes.addFlashAttribute("message", "操作成功");
}
return REDIRECT_LIST;
}
@GetMapping("blogs/{id}/delete")
public String delete(@PathVariable Long id, RedirectAttributes attributes){
blogService.deleteBlog(id);
attributes.addFlashAttribute("message","删除成功");
return REDIRECT_LIST;
}
}
四、创建查询对象类
创建 BlogQuery
package com.example.vo;
public class BlogQuery {
private String title;
private Long typeId;
private boolean recommend;
}
标签:Blog,SpringBoot,博客,blog,v1.0,springframework,import,org,id 来源: https://blog.csdn.net/qq_41230572/article/details/112426738
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。