简体   繁体   English

在JPA中使用oneToMany关系时,Postgresql在列中抛出空值违反了非空约束

[英]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.xmldb-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.并在更新/添加PostCommentPost类中的列表时使用此方法。

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.

相关问题 带有postgresql的串行列上的Spring Data JPA“xxx列中的空值违反非空约束” - Spring Data JPA "null value in column xxx violates not-null constraint" on serial column with postgresql 关系“invoice”的“header_id”列中的 JPA null 值违反 PostgresSQL 的非空约束 - JPA null value in column "header_id" of relation "invoice" violates not-null constraint with PostgresSQL 错误:关系 xxx 的“id”列中的 null 值违反非空约束 - Spring 数据 JPA - ERROR: null value in column "id" of relation xxx violates not-null constraint - Spring Data JPA 突发错误:org.postgresql.util.PSQLException:错误:列“id”中的空值违反非空约束 - Sudden error: org.postgresql.util.PSQLException: ERROR: null value in column “id” violates not-null constraint org.postgresql.util.PSQLException:错误:“ category_id”列中的空值违反了非空约束 - org.postgresql.util.PSQLException: ERROR: null value in column “category_id” violates not-null constraint org.postgresql.util.PSQLException:错误:列“id”中的空值违反非空约束 - org.postgresql.util.PSQLException: ERROR: null value in column “id” violates not-null constraint Postgresql 抛出 null 列“id”中的值违反了 GenerationType.IDENTITY 的非空约束 - Postgresql throws null value in column "id" violates not-null constraint for GenerationType.IDENTITY null 关系“技术”的“id”列中的值违反了非空约束 (PostgreSQL) - null value in column "id" of relation "technologies" violates not-null constraint (PostgreSQL) 如何修复列“id”中的&#39;null值违反了非空约束&#39;&#39; - How to fix ''null value in column “id” violates not-null constraint'' 错误:null 列“XX”中的值违反了非空约束 SPRING - ERROR: null value in column "XX" violates not-null constraint SPRING
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM