Serialize bi-directional JPA entities to JSON with jackson

I think you have to choose between the @JsonIdentityInfo and the @JsonBackReference / @JsonManagedReference.

I would go with : @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id") on your entities, removes @JsonBackReference / @JsonManagedReference pairs.

And add @JsonIgnore on the fields you want to exclude.


You can use JsonManagedReference / JsonBackReference and at the same time use JsonIdentityInfo to complement bidirectional relationships.

In question Class:

// bi-directional one-to-many association to Answer (Question is owner)
@JsonManagedReference
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@QuestionAnswers")
private Set<Answer> answers = new HashSet<>();

In answer Class: // bi-directional many-to-one association to Question

@JsonBackReference
@ManyToOne
@JoinColumn(name = "questionId", referencedColumnName="id", foreignKey = @ForeignKey(name = "fk_answer_question"))
private Question question;

If you need parent reference in child object, remove Managed / Back Reference, this works fine for me.