请用springboot帮我写一个用户发送评论与回复评论的代码
时间: 2023-05-19 18:05:30 浏览: 60
好的,以下是使用 Spring Boot 编写用户发送评论与回复评论的代码:
首先,我们需要创建一个 Comment 实体类,用于存储评论的信息:
```java
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String content;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
@ManyToOne(fetch = FetchType.LAZY)
private Comment parentComment;
@OneToMany(mappedBy = "parentComment", cascade = CascadeType.ALL)
private List<Comment> childComments = new ArrayList<>();
// getters and setters
}
```
接下来,我们需要创建一个 CommentRepository 接口,用于操作 Comment 实体类:
```java
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findByPostAndParentCommentNull(Post post, Sort sort);
}
```
然后,我们需要创建一个 CommentService 类,用于实现评论的业务逻辑:
```java
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
public List<Comment> getCommentsByPost(Post post) {
Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
return commentRepository.findByPostAndParentCommentNull(post, sort);
}
public Comment saveComment(Comment comment) {
Long parentCommentId = comment.getParentComment().getId();
if (parentCommentId != null) {
Comment parentComment = commentRepository.findById(parentCommentId).orElse(null);
comment.setParentComment(parentComment);
}
comment.setCreateTime(new Date());
return commentRepository.save(comment);
}
}
```
最后,我们需要创建一个 CommentController 类,用于处理评论相关的请求:
```java
@RestController
@RequestMapping("/comments")
public class CommentController {
@Autowired
private CommentService commentService;
@GetMapping("/{postId}")
public List<Comment> getCommentsByPost(@PathVariable Long postId) {
Post post = new Post();
post.setId(postId);
return commentService.getCommentsByPost(post);
}
@PostMapping
public Comment saveComment(@RequestBody Comment comment) {
return commentService.saveComment(comment);
}
}
```
以上就是使用 Spring Boot 编写用户发送评论与回复评论的代码。