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

泪湿孤枕 提交于 2019-12-08 03:31:07

问题


I have a Province class like below:

public class Province {

    @Id
    Long id;

    @Column(nullable = false)
    String name;

    @JsonManagedReference
    @OneToMany(mappedBy = "province")
    List<City> cities;

}

and a City class like below:

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

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "province_id")
    Province province;

}

now I want to have pronivce_id (as an int value not object) in JSON result of City in REST result.

How can I do this?


回答1:


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.



来源:https://stackoverflow.com/questions/49832919/how-to-include-join-column-in-json-result-with-jpahibernate

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