Skip to content
Advertisement

Stack overflow error for hibernate one-to-one mapping with Spring Data JPA

My problem is similar to this one https://discourse.hibernate.org/t/hibernate-throws-org-hibernate-id-identifiergenerationexception-attempted-to-assign-id-from-null-one-to-one-property/1777 but I am getting a different exception after applying the answer from this thread.

My entities:

JavaScript
JavaScript

Controller with corresponding Spring Data Repository:

JavaScript

With this payload:

JavaScript

I am getting an endless nested response with proper fields(distributor -> location -> distributor -> location ..), which ends with SO Error:

JavaScript

I can’t fathom why does this happen, I followed all available tutorials.

Advertisement

Answer

That’s because there is a cyclic dependency between Location and Distributor.

As both have reference to each other, they keep serializing inner reference.

You can avoid that using jackson annotation @JsonBackReference and @JsonManagedReference.

JsonBackReference: skips serialization of annotated property

JsonManagedReference : forward reference and serializes annotated property

In your case, this should work.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement