如何使用JPA + Hibernate在json结果中包括连接列 [英] How to include join column in json result with JPA+Hibernate
问题描述
我有一个Province
类别,如下所示:
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;
}
和如下的City
类:
public class City{
@Column(nullable = false)
String name;
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "province_id")
Province province;
}
现在我想在REST结果中City的JSON结果中包含pronivce_id
(作为int值而不是对象).
now I want to have pronivce_id
(as an int value not object) in JSON result of City in REST result.
我该怎么做?
推荐答案
您可以返回带有JsonIdentityInfo
和JsonIdentityReference
Jackson批注的province_id
.
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;
}
此问题与Hibernate + JPA无关.您只需要正确映射province
对象即可.但是您将面临一些问题:
1)延迟加载问题.要映射所有省份ID,您需要将其加载到内存中.因此,您不能使用fetch = LAZY
,并且映射不正确会导致N + 1提取问题.
2)此JSON映射将应用于序列化和反序列化.因此,如果您不仅要将此实体用作Query POJO(用于JSON视图等),还用作Command对象(例如:用于创建和更新),则需要将Province对象作为id
字段传递,而不是作为目的.
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.
这篇关于如何使用JPA + Hibernate在json结果中包括连接列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!