【发布时间】:2020-02-10 21:57:54
【问题描述】:
我有 comment 实体,它有 user_id 和 project_id 作为外键。并且 cmets 可以在parent_commnent_id 提到的同一个表中具有父子关系。
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "comment_id")
private int commentId;
@ManyToOne
@JsonIgnore
@JoinColumn(name = "project_id")
private Project projectId;
@Column(name = "comment")
private String comment;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private RegisteredUser user;
@ManyToOne
@JsonIgnore
@JoinColumn(name = "Parent_comment_id")
public Comment ParentCommentId;
@OneToMany(mappedBy = "ParentCommentId")
public List<Comment> childComments = new ArrayList<Comment>();
public int getCommentId() {
return commentId;
}
public void setComment(String comment) {
this.comment = comment;
}
public Project getProjectId() {
return projectId;
}
public void setProjectId(Project projectId) {
this.projectId = projectId;
}
public RegisteredUser getUser() {
return user;
}
public void setUser(RegisteredUser user) {
this.user = user;
}
public String getComment() {
return comment;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
}
我手动插入了一些数据
INSERT INTO comment (comment, Parent_comment_id, project_id, user_id) VALUES ( 'first comment', null, 1, 1);
INSERT INTO comment (comment, Parent_comment_id, project_id, user_id) VALUES ( 'first child comment', 1, 1, 2);
这让我回了这个
但我无法通过邮递员发布数据。这个我试过了
{
"comment": "third comment",
"userId": 2,
"projectId" : 3,
"parentCommentId" : 2
}
插入数据但将userId、projectId和parentCommentId作为null返回。
我也试过这个。
{
"comment": "third comment",
"user": {
"userId" : 2
}
}
这给了我 500 错误。
【问题讨论】:
-
你写过任何控制器类和服务类来返回这个吗,接下来只传递一个唯一的 id 以便它为你提供例外的数据
-
是的,在控制器中我将评论对象传递给存储库的保存功能。
标签: java spring-boot gradle spring-data-jpa