实习笔记9

线上实习第九天回顾

今天是线上实习的第九天,任务是在此前的项目基础上完成新闻管理的条件查询、分页展示、新增和编辑功能。

源码展示

1、项目结构如下图所示
在这里插入图片描述
2、dao.NewRepository类

package com.zr0726.news.dao;

import com.zr0726.news.po.News;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

public interface NewRepository extends JpaRepository<News,Long> , JpaSpecificationExecutor<News> {

//    @Query("select n from News n where n.title like?1 or n.content like ?1")
//    Page<News> findByQuery(String query, Pageable page);

}

3、po包下新建News类

package com.zr0726.news.po;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name="t_news")
public class News {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    @Basic(fetch = FetchType.LAZY)
    @Lob
    private String content;
    private String firstPicture;
    private String flag;
    private String views;
    private boolean appreciation;
    private boolean shareStatement;
    private boolean commentable;
    private boolean published;
    private boolean recommend;
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;

    @ManyToOne
    private Type type;
    @ManyToOne
    private User user;
    @ManyToMany(cascade = CascadeType.PERSIST)//级联
    private List<Tag> tags = new ArrayList<>();
    @Transient
    private String tagIds;

    private String description;

    public News() {
    }



    public Long getId() {
        return id;
    }

    public void setId(Long 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 String getFirstPicture() {
        return firstPicture;
    }

    public void setFirstPicture(String firstPicture) {
        this.firstPicture = firstPicture;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public String getViews() {
        return views;
    }

    public void setViews(String views) {
        this.views = views;
    }

    public boolean isAppreciation() {
        return appreciation;
    }

    public void setAppreciation(boolean appreciation) {
        this.appreciation = appreciation;
    }

    public boolean isShareStatement() {
        return shareStatement;
    }

    public void setShareStatement(boolean shareStatement) {
        this.shareStatement = shareStatement;
    }

    public boolean isCommentable() {
        return commentable;
    }

    public void setCommentable(boolean commentable) {
        this.commentable = commentable;
    }

    public boolean isPublished() {
        return published;
    }

    public void setPublished(boolean published) {
        this.published = published;
    }

    public boolean isRecommend() {
        return recommend;
    }

    public void setRecommend(boolean recommend) {
        this.recommend = recommend;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    public String getTagIds() {
        return tagIds;
    }

    public void setTagIds(String tagIds) {
        this.tagIds = tagIds;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void init(){
        this.tagIds = tagsToIds(this.getTags());
    }
    private String tagsToIds(List<Tag> tags){
        if(!tags.isEmpty()){
            StringBuffer ids = new StringBuffer();
            boolean flag = false;
            for(Tag tag:tags){
                if(flag){
                    ids.append(",");
                }else{
                    flag=true;
                }
                ids.append(tag.getId());
            }
            return ids.toString();
        }else{
            return tagIds;
        }
    }
    @Override
    public String toString() {
        return "News{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", firstPicture='" + firstPicture + '\'' +
                ", flag='" + flag + '\'' +
                ", views='" + views + '\'' +
                ", appreciation=" + appreciation +
                ", shareStatement=" + shareStatement +
                ", commentable=" + commentable +
                ", published=" + published +
                ", recommend=" + recommend +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", type=" + type +
                ", user=" + user +
                ", tags=" + tags +
                ", tagIds='" + tagIds + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

Tag类也新增了两个方法

   public List<News> getNewsList() {
        return newsList;
    }

    public void setNewsList(List<News> newsList) {
        this.newsList = newsList;
    }

Type类也新增了两个方法

 public List<News> getNews() {
        return news;
    }

    public void setNews(List<News> news) {
        this.news = news;
    }

User类新增getNewsList方法和setNewsList方法

 public List<News> getNewsList() {
        return newsList;
    }

    public void setNewsList(List<News> newsList) {
        this.newsList = newsList;
    }

4、新增NewService类

package com.zr0726.news.service;

import com.zr0726.news.po.News;
import com.zr0726.news.vo.NewsQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface NewService {

    Page<News> listNew(Pageable pageable, NewsQuery newsQuery);
    News saveNew(News news);

    News getNew(Long id);

    News updateNew(Long id,News news);
}

NewService接口的实现类NewServiceImpl类

package com.zr0726.news.service.impl;

import com.zr0726.news.dao.NewRepository;
import com.zr0726.news.po.News;
import com.zr0726.news.service.NewService;
import com.zr0726.news.vo.NewsQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

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 NewServiceImpl implements NewService {

    @Autowired
    private NewRepository newRepository;
    //新闻管理中的新闻列表(包含了查询)
    @Override
    public Page<News> listNew(Pageable pageable, NewsQuery newsQuery) {
        return newRepository.findAll(new Specification<News>() {
            @Override
            public Predicate toPredicate(Root<News> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(!"".equals(newsQuery.getTitle())&&newsQuery.getTitle()!=null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+newsQuery.getTitle()+"%"));
                }
                if(newsQuery.getTagId()!=null){
                    predicates.add(cb.equal(root.get("type").get("id"),newsQuery.getTagId()));
                }
                if(newsQuery.isRecommend()){
                    predicates.add(cb.equal(root.get("recommend"),newsQuery.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public News saveNew(News news) {
        if(news.getId()==null){
            news.setCreateTime(new Date());
            news.setUpdateTime(new Date());
        }
        return newRepository.save(news);
    }

    @Override
    public News getNew(Long id) {
        return newRepository.findById(id).orElse(null);
    }

    @Override
    public News updateNew(Long id, News news) {
        News news1= newRepository.findById(id).orElse(null);
        if(news1==null){
            System.out.println("未获得更新对象");
        }
        BeanUtils.copyProperties(news,news1);
        news1.setUpdateTime(new Date());
        return newRepository.save(news1);
    }
}

TagServiceImpl新增ListTag方法

   @Override
    public List<Tag> listTag(String ids) {
        return tagRepository.findAllById(convertToList(ids));
    }
    private List<Long> convertToList(String ids){
        System.out.println("service接收到ids为:"+ids);
        List<Long> list  = new ArrayList<>();
        if(!"".equals(ids)&&ids!=null){
            String[] idArray = ids.split(",");
            for(int i = 0;i<idArray.length;i++){
                list.add(new Long(idArray[i]));
            }
        }
        System.out.println("service中处理完成后的id list"+list);
        return list;
    }

5、新增vo包,新建NewsQuery类

package com.zr0726.news.vo;

public class NewsQuery {

    private String title;

    private Long tagId;

    private boolean recommend;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getTagId() {
        return tagId;
    }

    public void setTagId(Long tagId) {
        this.tagId = tagId;
    }

    public boolean isRecommend() {
        return recommend;
    }

    public void setRecommend(boolean recommend) {
        this.recommend = recommend;
    }

    @Override
    public String toString() {
        return "NewsQuery{" +
                "title='" + title + '\'' +
                ", tagId=" + tagId +
                ", recommend=" + recommend +
                '}';
    }
}

6、admin包新增NewsController类

package com.zr0726.news.web.admin;

import com.zr0726.news.po.News;
import com.zr0726.news.po.User;
import com.zr0726.news.service.NewService;
import com.zr0726.news.service.TagService;
import com.zr0726.news.service.TypeService;
import com.zr0726.news.vo.NewsQuery;
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 NewController {

    private static final String INPUT = "admin/news-input";

    private static final String LIST = "admin/news";

    private static final String REDIRECT_LIST = "redirect:/admin/news";

    @Autowired
    private NewService newService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/news")
    public String news(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                       Pageable pageable, NewsQuery newsQuery, Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("page",newService.listNew(pageable,newsQuery));
        return LIST;
    }
    @PostMapping("/news/search")
    public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                               Pageable pageable, NewsQuery newsQuery, Model model){
        model.addAttribute("page",newService.listNew(pageable,newsQuery));
        return "admin/news :: newsList";
    }
    public void setTypeAndTag(Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagService.listTag());
    }
    @GetMapping("/news/input")
    public String input(Model model){
//        model.addAttribute("types",typeService.listType());
//        model.addAttribute("tags",tagService.listTag());
        setTypeAndTag(model);
        return INPUT;
    }
    @GetMapping("/news/{id}/toUpdate")
    public String toUpdate(@PathVariable Long id, Model model){
        setTypeAndTag(model);
        News news = newService.getNew(id);
        news.init();
        model.addAttribute("news",news);
        return INPUT;
    }
    @PostMapping("/news/add")
    public String post(News news, RedirectAttributes attributes, HttpSession session){
        System.out.println("controller接受的news为:"+news);
        news.setUser((User) session.getAttribute("user"));
        news.setType(typeService.getType(news.getType().getId()));
        news.setTags(tagService.listTag(news.getTagIds()));
        News news1;
        if(news.getId()==null){
            news1 = newService.saveNew(news);
        }else{
            news1 = newService.updateNew(news.getId(),news);
        }
        if(news1 == null){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return REDIRECT_LIST;
    }
}

项目运行结果

新闻管理界面
在这里插入图片描述

查询新闻
在这里插入图片描述

新增新闻
在这里插入图片描述
发布成功
在这里插入图片描述

编辑新闻
在这里插入图片描述
编辑成功
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值