2017-05-19 39 views
0

我想要做一個項目與一些基本的ORM關係和REST控制器發送jsons。春季啓動JPA - json與嵌套的對象和編號

我的一個的POJO看起來像這樣:

@Entity 
@Table(name = "product_models") 
public class ProductModel extends BaseEntityWithName { 
    @ManyToOne(fetch = FetchType.EAGER) 
    @JoinColumn(name = "manufacturer_id") 
    @JsonManagedReference 
    private ProductManufacturer manufacturer; 

    --constr + setters + getters-- 

} 

當進行GET請求,響應看起來是這樣的:

{ 
    id: 1, 
    name: "Product 1", 
    manufacturer: { 
        id: 1, 
        name: "Manufacturer 1" 
       } 
} 

有沒有什麼辦法讓該請求是這個樣子?(返回外鍵ID和嵌套對象)

{ 
    id: 1, 
    name: "Product 1", 
    manufacturer_id: 1 
    manufacturer: { 
        id: 1, 
        name: "Manufacturer 1" 
       } 
} 

回答

1

你可以添加一個額外的get ter to ProductModel and make them @Transient

@JsonProperty("manufacturer_id") 
@Transient 
public Long getManufacturerId() { 
    return manufacturer == null ? null : manufacturer.getId(); 
} 
+0

非常感謝你,男人!我一直試圖讓這個工作在過去的4個小時,並且從來沒有把它當成解決方案。 –

+0

@IonuţZamfir歡迎:) –