Spring Data Rest - 隐藏而不是暴露 ID

Spring Data Rest - hide instead of exposing ID

我有一个实体 class,它有一个映射为 @Id 的自然 ID 字段,我没有任何代理 ID(仅为 table ID 发明的字段)字段。而且,在杰克逊编组 JSON 中,我看到一个额外的 id 暴露。

所以代替:

{
    "bin":"123456", ...
}

我明白了:

{
    "id":"123456", "bin":"123456", ...
}

我不想要,因为它们是重复的信息。我怎样才能防止这种情况发生?

我还没有接触过REST/MVC配置适配器;它们用于公开 ID classes,但我不希望那样。

豆子:

@Entity
@Data
@Table(name="bin_info")
public class BinInfo implements Serializable, Persistable<String> {
    @Id
    @NotBlank //this is for absent parameter. Not equal to Pattern regex check
    @Pattern(regexp = "^\d{6,8}$") //6-8 digits
    @Column(name="bin")
    @JsonProperty("bin")
    private String bin;

    ...

我有这些依赖关系:

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-aop')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-undertow')
    runtime('com.h2database:h2')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('io.cucumber:cucumber-java:3.0.2')
    testCompile('io.cucumber:cucumber-junit:3.0.2')
    testCompile('io.cucumber:cucumber-spring:3.0.2')
}

Spring 启动 2.0.3.

尝试使用 @NaturalId 而不是 @Id 进行注释。

尝试用 @JsonIgnore

注释该字段

谢谢大家,我认为这与 Spring 或 Jackson 的某些配置有关,这些配置会自动公开使用 @Id 映射的字段。我只能猜测,因为没有时间确认。

一些同事建议我定义一个 DTO 而不是将 @Jsonxxx 注释放在 class 中,说模型代表数据模型并且与 table 相关,而DTO与视图层有关。所以我做到了,现在一切都很好。

现在模型没有 id 字段和 @JsonProperty/@JsonIgnore:

@Entity
@Data
@Table(name="bin_info")
public class BinInfo implements Serializable, Persistable<String> {
    @Id
    @NaturalId
    @NotBlank //this is for absent parameter. Not equal to Pattern regex check
    @Pattern(regexp = "^\d{6,8}$") //6-8 digits
    @Column(name="bin")
    //@JsonProperty("bin")
    private String bin;

    ...

而且DTO完全没有@Id:

@Data
public class BinInfoDTO {
    @JsonProperty("bin")
    private String bin;

    @JsonProperty("json_full")
    private String json_full;

    ...

当我检索一个实体时,我使用映射方法将 DTO 中需要的所有值设置为 DTO,并将其 return 设置为端点。那么JSON就正常了。

您必须从 id 字段实现获取和设置。