How to include join column in json result with JPA

2020-07-26 11:47发布

问题:

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.