0

I have two classes Post and Comment, one post can have multiple comments. So I have created my classes as follows:

Post:

@Entity
@Table(name = "posts")
public class Post extends AuditModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(max = 100)
    @Column(unique = true)
    private String title;

    @NotNull
    @Size(max = 250)
    private String description;

    @NotNull
    @Lob
    private String content;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "post")
    private Set<Comment> comments = new HashSet<>();
}

Comment:

@Entity
@Table(name = "comments")
public class Comment extends AuditModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Lob
    private String text;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "post_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    @JsonIdentityReference(alwaysAsId = true)
    @JsonProperty("post_id")
    private Post post;
}

Post method:

@PostMapping("/posts")
    public Post createPost(@Valid @RequestBody Post post) {
        return postRepository.save(post);
    }

Swagger request:

{
  "id": 0,
  "title": "string",
  "description": "string",
  "content": "string",
  "comments": [
    {
      "id": 0,
      "text": "string",
      "post_id": 0
    }
  ]
}

When I do a POST using the above schema, I am expecting that hibernate will insert data in both the tables. But instead, I get below error:

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unresolved forward references for: ; nested exception is com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Unresolved forward references for: 
 at [Source: (PushbackInputStream); line: 1, column: 117]Object id [1] (for `com.example.jpa.model.Post`) at [Source: (PushbackInputStream); line: 1, column: 115].]

Can someone please help me to understand this and how can I achieve my requirement?

csfragstaa
  • 145
  • 1
  • 2
  • 9

0 Answers0