欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【学习日记】(SpringBoot-part 4)新闻管理系统—添加和修改新闻功能

程序员文章站 2022-09-17 09:12:27
新闻管理系统的新闻添加和修改功能效果展示实现过程添加新闻功能和修改功能的实现机制是差不多的,因此放到一起实现效果展示实现过程添加实体类且声明与其他实体关系在po文件下添加News实体信息如下,并在实体信息中声明和其他实体的关系实体关系:News to Type:n:1News to User:n:1News to Tags:n:n 因为News和Tags的实体关系为多对多,所以需要指定级联,生成一个News-Tag关系表@Entity@Table(name =...

新闻管理系统的新闻添加和修改功能

添加新闻功能和修改功能的实现机制是差不多的,因此放到一起实现

效果展示

【学习日记】(SpringBoot-part 4)新闻管理系统—添加和修改新闻功能【学习日记】(SpringBoot-part 4)新闻管理系统—添加和修改新闻功能【学习日记】(SpringBoot-part 4)新闻管理系统—添加和修改新闻功能【学习日记】(SpringBoot-part 4)新闻管理系统—添加和修改新闻功能

实现过程

  1. 添加实体类且声明与其他实体关系

    在po文件下添加News实体信息如下,并在实体信息中声明和其他实体的关系
    实体关系:
    News to Type : n:1
    News to User : n:1
    News to Tags : n:n 因为News和Tags的实体关系为多对多,所以需要指定级联,生成一个News-Tag关系表

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

    @Id //主键标识
    @GeneratedValue(strategy = GenerationType.IDENTITY)  //自增
    private Long id;
    private String title;

    @Basic(fetch = FetchType.LAZY)        //懒加载  需要用到的时候再加载
    @Lob          //存储量较大的内容用到@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;
    //还要加标签tag
    @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 isCommentabled() {
        return commentabled;
    }

    public void setCommentabled(boolean commentabled) {
        this.commentabled = commentabled;
    }

    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;
    }

    //对一对多的标签进行处理  如一个新闻有id为12345的tag  初始化为 1,2,3,4,5
    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 +
                ", commentabled=" + commentabled +
                ", published=" + published +
                ", recommend=" + recommend +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", type=" + type +
                ", user=" + user +
                ", tags=" + tags +
                ", tagIds='" + tagIds + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}
  1. 新建vo文件
    新建一个vo文件夹,创建一个NewQuery类,该目录和平常用的Util类似,是用来存放工具类的,在这里我们声明的NewQuery类,用来对接下来的新闻查询功能,进行一个预处理,文件目录如下
    【学习日记】(SpringBoot-part 4)新闻管理系统—添加和修改新闻功能
//对查询条件进行预处理
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 +
                '}';
    }
}
  1. 声明一个dao接口
    在dao目录下新建一个NewRepository,只需要声明继承Jpa,使用jpa中的方法
public interface NewRepository extends JpaRepository<News,Long> , JpaSpecificationExecutor<News> {   
}
  1. Service添加接口方法和实现方法
    新建一个NewService接口
public interface NewService {

    Page<News> listNew(Pageable pageable, NewQuery newQuery);

    //新增
    News saveNew(News news);
    //更新
    News getNew(Long id);
    News updateNew(Long id,News news);
}

在Impl中新建一个方法实现NewService接口中的方法

由于查询数据一共可以结合三种方式进行查询,所以在listNew方法中结合之前的NewQuery实现查询数据的预处理,以及将数据结果显示

@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       //criteriaQuery查询条件的容器  criteriaBuilder表达式
            public Predicate toPredicate(Root<News> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(!"".equals(newQuery.getTitle()) && newQuery.getTitle()!=null) {   //标题不为空
                    predicates.add(cb.like(root.<String>get("title"), "%"+newQuery.getTitle()+"%"));
                }
                if(newQuery.getTypeId()!=null){   //根据分类查
                    predicates.add(cb.equal(root.get("type").get("id"),newQuery.getTypeId()));
                }
                if(newQuery.isRecommend()){ //根据是否被推荐查询
                   predicates.add(cb.equal(root.get("recommend"),newQuery.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);
    }
}
  1. 修改控制器
@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 TagService tagService;

    @Autowired
    private TypeService typeService;

    @GetMapping("/news")
    public String news(@PageableDefault(size = 3,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 = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                               Pageable pageable, NewQuery newQuery, Model model){

        model.addAttribute("page",newService.listNew(pageable,newQuery));
        System.out.println(model);
        return "admin/news :: newsList";
    }

    //用来在修改和新增news页面显示所有type和tag的
    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);
        System.out.println("运行到这里了吗?"+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){
        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;

    }
}
  • news方法:
@GetMapping("/news")
public String news(@PageableDefault(size = 3,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;
}

用来在新闻界面将数据库中所有信息展示出,按更新时间进行排序,这里新在typeService中声明一个接口listType

//不分页的List  在查找新闻界面显示出
List<Type> listType();
@Override
public List<Type> listType() {
    return typeRepository.findAll();
}
  • search方法
@PostMapping("/news/search")
public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                            Pageable pageable, NewQuery newQuery, Model model){
     model.addAttribute("page",newService.listNew(pageable,newQuery));
     System.out.println(model);
     return "admin/news :: newsList";
 }

同样按照更新时间进行排序,这里使用之前Impl中实现的查询方法

  • add方法
//用来在修改和新增news页面显示所有type和tag的
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;
}

input.html中添加指向add路由

//跳转页面
@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;
}

在新建时涉及到选择已存在的tag和type,所以需要再去TagService中新建一个查询所有tag信息的接口并实现

//列所有标签
List<Tag> listTag();
@Override
public List<Tag> listTag() {
    return tagRepository.findAll();
}
  • update方法
@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;
}

更新和新建类似,需要判断是否存在id,不存在即新建,存在即更新,需要在News实体类中进行一个初始化和判断处理

//对一对多的标签进行处理  如一个新闻有id为12345的tag  初始化为 1,2,3,4,5
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;
    }
}

本文地址:https://blog.csdn.net/qq_42756396/article/details/107665134

相关标签: 个人学习