2017-05-19 42 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欢迎:) –