Spring引导+休眠控制器

我试图做一个迷你论坛,我被​​卡住了。 它应该是什么,首先你创建一个帖子,写下主题信息,重定向到所有帖子并添加你创建的新帖子,用户点击帖子,并在下一页显示所有填写的信息。另外我做了一个评论系统,我的每一篇文章都有评论,所以问题出现在我的代码中,当我试图做出这些评论的工作时,它的工作原理是这样的:无论你选择什么post ID,都显示所有确实存在的评论,所以我改变了,失败了。 可能有人解释我,如何使Hibernate正确。

PostController是:注意方法seeMessage,它通过id和显示消息finders。

package com.pandora.controllers;


import com.pandora.domain.Post;
import com.pandora.services.CommentService;
import com.pandora.services.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
@RequestMapping("/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private CommentService commentService;

    @RequestMapping
    public String findAll(Model model) {
        model.addAttribute("posts", postService.findAll());
        return "post/post";
    }

    @RequestMapping(value = "/click", method = RequestMethod.GET)
    public String click() {
        return "post/new";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addPost(@ModelAttribute Post post) {
        postService.addPost(post);
        return "redirect:/posts";
    }

    @RequestMapping(value = "/{title}/find", method = RequestMethod.GET)
    public String findByName(@PathVariable String title) {
        postService.findByTitle(title);
        return "redirect:/posts";
    }

    @RequestMapping(value = "/{id}/see", method = RequestMethod.GET)
    public String seeMessage(@PathVariable long id, Model model) {
        Post post = postService.findById(id);
        System.out.println("the id is " + id);
        System.out.println("the value of comments are " +post.getComments().size());

        model.addAttribute("post", post);
//        model.addAttribute("postMessage", post.getComments());

        return "post/postmessage";

    }

    @RequestMapping(value = "/{id}/delete")
    public String delete(@PathVariable long id) {
        postService.delete(id);
        return "redirect:/posts";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "login";
    }

}

CommentController是:在这里注意方法addComment,首先我从什么id发布它去了,并在此之后,我不得不添加评论创建职位。

package com.pandora.controllers;

import com.pandora.domain.Comment;

import com.pandora.domain.Post;
import com.pandora.services.CommentService;
import com.pandora.services.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/comments")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private PostService postService;

    @RequestMapping(value = "/post/{postId}/comment", method = RequestMethod.POST)
    public String addComment(@PathVariable long postId, @ModelAttribute Comment comment){

        Post post = postService.findById(postId);

        System.out.println(post.getId());
        System.out.println(comment.getMessage());

        List comments = new ArrayList();

        comments.add(commentService.addComment(comment));

        post.setComments(comments);

        return "redirect:/posts";
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable long id){
        commentService.delete(id);
        return "redirect:/posts";
    }

}

邮政实体是:

package com.pandora.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

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

@Entity
@Setter
@Getter
@NoArgsConstructor
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "post")
    private List comments;

    @Column(length = 10000)
    private String message;

    private String title;
}

PostService是:

package com.pandora.services;

import com.pandora.domain.Post;
import com.pandora.domain.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {

    @Autowired
    private PostRepository postRepository;

    public Post addPost(Post post){
        return postRepository.saveAndFlush(post);
    }

    public List findAll(){
        return postRepository.findAll();
    }

    public Post findByTitle(String title){
        return postRepository.findByTitle(title);
    }

    public Post findById(long id){
        return postRepository.findOne(id);
    }

    public void delete(long id){
        postRepository.delete(id);
    }

}

评论实体是:

package com.pandora.domain;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;

@Entity
@Setter
@Getter
@NoArgsConstructor
public class Comment {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToOne(fetch = FetchType.EAGER)
    private Post post;

    private String message;

}

和CommentService是:

package com.pandora.services;

import com.pandora.domain.Comment;
import com.pandora.domain.repositories.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    public Comment addComment(Comment comment){
        return commentRepository.saveAndFlush(comment);
    }

    public List findAll(){
        return commentRepository.findAll();
    }

    public void delete(long id){
        commentRepository.delete(id);
    }

    public Comment findOne(long id){
        return commentRepository.findOne(id);
    }

}

并显示由id选择的帖子的html是:这里要注意th:每个div容器。 我从列表中检索从PostController注释中删除。 但它不起作用,因为当我这样做时,它总是空的。 我不知道为什么它是空的。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      layout:decorator="layout">

<div layout:fragment="content">

    <h2 align="center">
        <h2 align="left">
            <div th:text="${post.title}"></div>
        </h2>
    </h2>

    <h4 align="center">
        <div th:text="${post.message}"></div>
    </h4>
    <hr/>
    <h4>Comments:</h4>
    <br/>

    <h4>
        <div th:each="comments : ${post}">
           
            <label for="username"><div th:inline="text">[[${#httpServletRequest.remoteUser}]]: </div> </label>
            <div  th:each="comment : ${comments.comments}">
                <div  id="username" th:text="${comment}"></div>
            </div>
        </div>
    </h4>

    <br/>
    <form method="post" name="comment_form" id="comment_form" th:action="@{'/comments/post/{id}/comment'(id=${post.id}) }" role="form">
        <div class="form-group">
            <label for="message">Comment</label>
            <textarea rows="5" class="form-control" id="message" name="message"/>
        </div>
        <button type="submit" id="submit" class="btn btn-primary">Submit</button>
    </form>

</div>

</html>

您还需要更改控制器。 想想这样的事情,你现在有一个评论为零的帖子。 然后用户在PostController方法上发表评论说:

 @RequestMapping(value = "/post/{postId}/addComment", method = RequestMethod.POST)
            public String addPost(@PathVariable("postId")long id, @ModelAttribute Comment comment) {
                postService.addComment(id, comment);
                return "redirect:/to_whatever";
            }

在你的PostService中,你可能想添加下面的函数:

   public Post addComment(long id, Comment comment){
       Post post = postRepository.findOne(id);
       post.getComments().add(comment);
       return postRepository.saveAndFlush(post);
    }

相应地更改您的用户界面邮政电话 而且,这也将实现检索部分。 假设你想获得一篇文章的评论,你需要做的就是通过id(或者任何其他唯一标识符)查找帖子,并且执行post.getComments();

Embeddable将在帖子和评论之间建立OneToMany类型的关系。 请参阅此处了解更多详情。

在数据库级别,你会有这样的事情:

POST TABLE
post_id     post_name
  1            A
  2            B



POST_COMMENTS TABLE
post_id     message
  1            C
  1            D
  2            E
  2            F

希望这可以解决问题。


根据你的情况,这是我的理解:你有一个帖子和一些相关的评论。 但是,当您尝试检索特定帖子的评论时,您会看到所有评论(来自其他帖子)。

假设如上所述,我建议您不要将评论视为单独的实体,因为评论只会在有帖子发表时才会出现,而评论必须与单个帖子相关联。 @Embeddable可能对此有所帮助。

我的建议是尝试这样的事情:

使评论可嵌入:

@Embeddable
public class Comment {
    private String message;
    ...
    ...
    //Any other properties you might need to add
}

在邮政实体中,进行以下更改:

@Entity
@Setter
@Getter
@NoArgsConstructor
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ElementCollection(fetch=FetchType.EAGER)
    private List<Comment> comments = new ArrayList<>();

    @Column(length = 10000)
    private String message;

    private String title;
}

在此之后,您可能想放弃CommentService和CommentRepository,因为它们不再需要。 让我知道这是否有帮助。

链接地址: http://www.djcxy.com/p/48837.html

上一篇: Spring boot + hibernate controller

下一篇: How to render partial view in Spring MVC