springboot实现新闻管理功能

接着昨天的项目继续开发:
新闻实体类:

@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 commentabled;
    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;//接收前端页面传过来的标签Id

    private String description;
}

创建vo包,VO是指value object值对象,通常用于业务层之间的数据传递,和PO一样也是仅仅包含数据而已。一般来说,PO只能用在数据层,VO用在商业逻辑层和表示层。在vo包下创建NewsQuery类,我们利用NewsQuery类专门处理新闻管理界面的条件查询。因为我们需要通过新闻的标题、类型以及是否被推荐作为条件来查询数据库里的新闻,所以我们就利用这三个属性来组成一个查询类。

public class NewQuery {
     
    private String title;
    private Long typeId;
    private boolean recommend;

    public String getTitle() {
     
        return title;
    }

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

    public Long getTypeId() {
     
        return typeId;
    }

    public void setTypeId(Long typeId) {
     
        this.typeId = typeId;
    }

    public boolean isRecommend() {
     
        return recommend;
    }

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

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

之后同样的,写对应的service和Impl:

@Service
public class NewServiceImpl implements NewService {
     

    @Autowired
    private NewRepository newRepository;

    //新闻管理中的列表(包括了查询)
    @Override
    public Page<News> listNew(Pageable pageable, NewQuery newQuery) {
     
        return newRepository.findAll(new Specification<News>() {
     
            @Override
            public Predicate toPredicate(Root<News> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
     
                List<Predicate> predicates=new ArrayList<>();
                if(!"".equals(newQuery.getTitle())&&newQuery.getTitle()!=null){
     
                    predicates.add(criteriaBuilder.like(root.<String>get("title"),"%"+newQuery.getTitle()+"%"));
                }
                if(newQuery.getTypeId()!=null){
     
                    predicates.add(criteriaBuilder.equal(root.get("type").get("id"),newQuery.getTypeId()));
                }
                if(newQuery.isRecommend()){
     
                    predicates.add(criteriaBuilder.equal(root.get("recommend"),newQuery.isRecommend()));
                }
                criteriaQuery.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);
    }
}

最后编写controller,实现对应的管理功能即可:

@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=5,sort={
     "updateTime"},direction = Sort.Direction.DESC)
                               Pageable pageable, NewQuery newQuery, Model model){
     
        model.addAttribute("types",typeService.listType());
        model.addAttribute("page",newService.listNew(pageable,newQuery));
        return LIST;
    }

    @PostMapping("/news/search")
    public String search(@PageableDefault(size=5,sort={
     "updateTime"},direction = Sort.Direction.DESC)
                                 Pageable pageable, NewQuery newQuery, Model model){
     

        model.addAttribute("page",newService.listNew(pageable,newQuery));
        return "admin/news::newsList";//指定页面中的newsList的片段
    }

    public void setTypeAndTag(Model model){
     
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagService.listTag());
    }

    @GetMapping("/news/input")
    public String input(Model model){
     
        setTypeAndTag(model);
        model.addAttribute("news",new News());
        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) {
     
        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;
    }
}

最后看看结果:
进入新闻界面
springboot实现新闻管理功能_第1张图片
点击新增,编写一条新闻:
springboot实现新闻管理功能_第2张图片
可以看到可以对新闻设置响应的分类和tag,都是我们之前写好的
在这里插入图片描述

你可能感兴趣的:(java)