![](/img/trans.png)
[英]How to get only ChildIds(Instead of whole child Object) from parent entity in Hibernate Jpa?
[英]Converting hibernate entity to JSON: oblectId instead of whole object
項目有兩個實體:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", nullable = true)
private City city;
...
}
和
@Entity
public class City {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "name", nullable = false)
private String name;
...
}
使用Gson或Jackson轉換為JSON的Cutomer實體
{
"id":1,
"city":{"id":1, "name":"New York"}
}
我希望它是轉換為
{
"id":1,
"city_id":1
}
我怎么能通過gson或jackson做到這一點?
這個問題可能對您有幫助。
我不知道是否有直接的方法可以實現這一目標,但有一些間接的方法可以實現。 例如,您可以將private City city
標記為transient
,然后您可以公開另一個名為city_id
字段,該字段只是城市ID。 它看起來像這樣:
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id", nullable = true)
private transient City city;
private int city_id;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.