博客管理
1、博客分页查询
2、博客新增
3、博客修改
4、博客删除
新建一个BlogService接口
页面编写
新建BlogServiceImpl实体类
页面代码
package net.tjl.blog.service;
import net.tjl.blog.NotFoundException;
import net.tjl.blog.dao.BlogRepository;
import net.tjl.blog.po.Blog;
import net.tjl.blog.po.Type;
import net.tjl.blog.util.MarkdownUtils;
import net.tjl.blog.util.MyBeanUtils;
import net.tjl.blog.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.*;
import java.util.*;
@Service
public class BlogServiceImpl implements BlogService {
@Autowired
private BlogRepository blogRepository;
@Override
public Blog getBlog(Long id) {
return blogRepository.getOne(id);
}
@Transactional
@Override
public Blog getAndConvert(Long id) {
Blog blog = blogRepository.getOne(id);
if (blog == null) {
throw new NotFoundException("该博客不存在");
}
Blog b = new Blog();
BeanUtils.copyProperties(blog,b);
String content = b.getContent();
b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
blogRepository.updateViews(id);
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(Long tagId, Pageable pageable) {
return blogRepository.findAll(new Specification<Blog>() {
@Override
public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
Join join = root.join("tags");
return cb.equal(join.get("id"),tagId);
}
},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,so