Spring Data Rest POST响应与GET响应不同

时间:2018-11-25 22:41:27

标签: spring hibernate jpa spring-data-rest

在我的Spring Data Rest项目中,我有一个Competition实体,它引用一个GeoLocation实体:

public class Competition {
    @Id
    private String uname;

    [...]

    @NotNull
    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private GeoLocation geoLocation;
}

public class GeoLocation {
    @Id private Long id;
    private Double latitude;
    private Double longitude;
}

由于每个Competition必须定义一个GeoLocation,因此Competition实体通过cascade处理创建。通过POST创建新的Competition实体时,收到以下响应:

{
    "uname": "Some Competition",
    "geoLocation": {
        [content of geoLocation]
    },
    "_links": {
        [...]
    }
}

但是当我调用新创建的竞赛时,GeoLocation的内容将被包装在content字段中。

{
    "uname": "Some Competition",
    "geoLocation": {
        "content": {
            [content of geoLocation]
        }        
    },
    "_links": {
        [...]
    }
}

我希望这两个请求都能提供相同的响应?

1 个答案:

答案 0 :(得分:1)

@JsonUnwrapped为我解决了这个问题:

public class Competition {
    @Id
    private String uname;

    [...]

    @NotNull
    @JsonUnwrapped
    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    private GeoLocation geoLocation;
}