Jackson bidirectional relationship (One-to-many) not working

混江龙づ霸主 提交于 2019-12-02 03:20:41

Because you are using the @JsonBackReference on the Customer property in the Loan entity, the Customer object will not included in the serialization. Use the @JsonManagedReference for the Customer in the Loan object and use @JsonBackReference on the Loan property in the Customer entity.

This will serialize the Customer property of your Loan entity. But the Customer object serialization will not contains the Loan property. You need to pick one side of the relationship to serialize.

To allow both side, use @JsonIdentityInfo annotation in your entity and remove the @JsonBackReference and @JsonManagedReference. You entities will be something like:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "customerId")
public class Customer implements Serializable {
    ...
}

The property of the @JsonIdentityInfo refer to your entity id property, for Customer this will be customerId. Do this for Loan and Item also.

This seems pretty old but let me put my coins here as well; I would seperate the entity and model. Means;

> Client <-> Application : Models
> 
> Application <-> Database : Entities

And your service layer or whatever layer you process data should make the conversion between entities and models.

  1. You get rid of recursion by returning data as your wish.
  2. You split the definitions between two different communication channels. This way you can decide what to show to your client and how to show your client as well. This will save your DB schema be exposed directly too.
  3. You can extend model as per your wish without touching to the DB backend.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!