How to include join column in json result with JPA+Hibernate

别说谁变了你拦得住时间么 提交于 2019-12-06 15:14:26

You can return province_id with JsonIdentityInfo and JsonIdentityReference Jackson annotations.

public class City {
    @Column(nullable = false)
    String name;

    @JsonProperty("province_id")
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    @JsonIdentityReference(alwaysAsId = true)
    @ManyToOne
    @JoinColumn(name = "province_id")
    Province province;

}

This issue is not related to Hibernate + JPA. All you need is to map province object correctly. But you will face some issues:
1) Lazy loading problem. To map all province ids you need to load them into memory. So you can't use fetch = LAZY and with incorrect mapping it will result with N+1 fetching problem.
2) This JSON mapping will apply to serialization and deserealization. So if you are going to use this entity not only as Query POJO (for JSON views etc), and also for Command objects (ex: for creation and update) - you will need pass province object as id field, not as an object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!