[英]Postgresql throw null value in column violates not-null constraint when using oneToMany relationship in JPA
I tried to test one-to-many relationship for Hibernate.我试图测试 Hibernate 的一对多关系。 I defined Post and PostComment entities as below: Post.java
我定义了 Post 和 PostComment 实体如下: Post.java
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "post")
public class Post {
@Id
@Column(name="post_id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long postId;
@Column(name="title")
private String title;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
orphanRemoval = true)
private List<PostComment> comments = new ArrayList<>();
public Post() {};
public Post(String title) {
this.title = title;
}
// Add getter and setter
}
PostComment.java发表评论.java
import javax.persistence.*;
@Entity
@Table(name = "post_comment")
public class PostComment {
@Id
@Column(name="comment_id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long commentId;
@Column(name="review")
private String review;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;
public PostComment() {};
public PostComment(String review) {
this.review = review;
}
// Add getter and setter
}
PostRepository.java PostRepository.java
public interface PostRepository extends JpaRepository<Post,Long> {
}
and db-changelog.xml和db-changelog.xml
<changeSet id="1" author="dev">
<createTable tableName="post_comment">
<column name="comment_id" type = "bigint">
<constraints nullable="false" primaryKey="true"></constraints>
</column>
<column name="review" type="varchar(255)"></column>
</createTable>
<createTable tableName="post">
<column name="post_id" type="bigint">
<constraints nullable="false" primaryKey="true"></constraints>
</column>
<column name="title" type = "varchar(255)"></column>
</createTable>
</changeSet>
Then, I used SpringJUnit to add a new post as in PostServiceITTest.java然后,我使用 SpringJUnit 在 PostServiceITTest.java 中添加了一个新帖子
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.Arrays;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@ActiveProfiles("devmock")
public class PostServiceITTest {
@Autowired
private PostRepository postRepository;
@Test
public void testAddPost(){
Post post = new Post(" Post 1");
PostComment postComment1 = new PostComment(" Post comment 1");
PostComment postComment2 = new PostComment(" Post comment 2");
post.setComments(Arrays.asList(postComment1,postComment2));
postRepository.save(post);
}
}
Unfortunately, the test throw a Postgresql error related to null-violate constraint:不幸的是,该测试抛出了一个与违反空约束相关的 Postgresql 错误:
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "post_id" violates not-null constraint
Detail: Failing row contains (null, Post 1).
I greatly appreciate your time.我非常感谢你的时间。
您似乎没有为post_id
传递值。
In your PostComment
class you have a field private Post post
.在您的
PostComment
类中,您有一个字段private Post post
。 I doubt if you are setting that field.我怀疑您是否正在设置该字段。
One option is to add Post post
as a constructor argument to PostComment
class (along with default constructor) and instantiating it along with Post
object as in:一种选择是将
Post post
作为构造函数参数添加到PostComment
类(以及默认构造函数)并将其与Post
对象一起实例化,如下所示:
public PostComment(String review, Post post) {
this.review = review;
this.post = post;
}
and while constructing the object use :并在构建对象时使用:
PostComment postComment1 = new PostComment(" Post comment 1", post);
instead of代替
PostComment postComment1 = new PostComment(" Post comment 1");
Or another approach would be to add scaffolding code in Post
class like:或者另一种方法是在
Post
类中添加脚手架代码,例如:
public void addPostComment(PostComment comment) {
comments.add(comment);
comment.setPost(this);
}
and use this method while updating/adding a PostComment
to the list in the Post
class.并在更新/添加
PostComment
到Post
类中的列表时使用此方法。
Below code may work;下面的代码可能有效; you may set the parent reference in child also...
您也可以在 child 中设置父引用...
{ Post post = new Post(" Post 1");
PostComment postComment1 = new PostComment(" Post comment 1");
postComment1.setPost(post); // < -- here
PostComment postComment2 = new PostComment(" Post comment 2");
postComment2.setPost(post); // < -- here
post.setComments(Arrays.asList(postComment1,postComment2));
postRepository.save(post);
}
If you are using lombok to generate toString() method, please exclude postComment.post to avoid infinite loop (that leads to stak overflow);如果您使用 lombok 生成 toString() 方法,请排除 postComment.post 以避免无限循环(导致 stak 溢出);
@ToString(exclude = { "post" })
public class PostComment{
// ...
}
I have resolved the issue by dropping my existed database and generating a new one with spring.jpa.hibernate.ddl-auto=create-drop
.我已经通过删除我现有的数据库并使用
spring.jpa.hibernate.ddl-auto=create-drop
生成一个新数据库来解决这个问题。 Of course, you can do it only if you have no valuable data in your database.当然,只有当您的数据库中没有有价值的数据时,您才能这样做。 Once you did it, change back to
spring.jpa.hibernate.ddl-auto=update
.完成后,改回
spring.jpa.hibernate.ddl-auto=update
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.