【发布时间】:2021-09-03 09:50:45
【问题描述】:
我来了
原因:org.postgresql.util.PSQLException: ERROR: null value in “post_id”列违反非空约束
当我试图坚持关注实体时。 该关系是一个 Post 到多个 post cmets 的 Post cmets,后者有更多 post cmets。如果可能的话,我也希望这种关系是单向的。你能指出我做错了什么吗?
SQL:
CREATE TABLE post
(
id BIGSERIAL PRIMARY KEY,
title TEXT
);
CREATE TABLE post_comment
(
id BIGSERIAL PRIMARY KEY,
review TEXT,
post_id BIGINT NOT NULL,
CONSTRAINT post_comment_fk FOREIGN KEY (post_id)
REFERENCES post (id)
);
CREATE TABLE more_post_comment
(
id BIGSERIAL PRIMARY KEY,
another TEXT,
post_comment_id BIGINT NOT NULL,
CONSTRAINT more_post_comment_fk FOREIGN KEY (post_comment_id)
REFERENCES post_comment (id)
);
存储库:
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
帖子:
@Entity(name = "Post")
@Table(name = "post")
@Data
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "post_id")
private List<PostComment> comments = new ArrayList<>();
}
发表评论:
@Entity(name = "PostComment")
@Table(name = "post_comment")
@Data
public class PostComment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String review;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "post_comment_id")
private List<MorePostComment> morePostComment = new ArrayList<>();
}
更多帖子评论:
@Entity(name = "MorePostComment")
@Table(name = "more_post_comment")
@Data
public class MorePostComment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String another;
}
测试:
@SpringBootTest
class Test {
@Autowired
private PostRepository postRepository;
@Test
public void should() {
Post post = new Post();
post.setTitle("title");
MorePostComment morePostComment = new MorePostComment();
morePostComment.setAnother("another");
List<MorePostComment> morePostComments = new ArrayList<>();
morePostComments.add(morePostComment);
PostComment postComment = new PostComment();
postComment.setReview("asd");
postComment.setMorePostComment(morePostComments);
List<PostComment> comments = new ArrayList<>();
comments.add(postComment);
post.setComments(comments);
post = postRepository.save(post);
assertThat(post.getComments()).isNotEmpty();
assertThat(post.getComments().get(0).getId()).isNotNull();
assertThat(post.getComments().get(0).getMorePostComment()).isNotEmpty();
}
}
【问题讨论】:
标签: java hibernate jpa spring-data