簡體   English   中英

將hibernate實體轉換為JSON:oblectId而不是整個對象

[英]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做到這一點?

這個問題可能對您有幫助。

Gson:如何在沒有注釋的情況下從序列化中排除特定字段

我不知道是否有直接的方法可以實現這一目標,但有一些間接的方法可以實現。 例如,您可以將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM