spring 数据 rest 中 POST 的只读属性

Read only properties for POST in spring data rest

是否有可能使某些信息只读于 spring jpa 实体的数据休息,即这些信息包含在 GET 中,但不能通过 POST 设置。

我必须自己做吗?

例子是:

public class Foo{

@Id
private String id;

@ReadOnlyProperty
private int updateCount;

}

现在您可以通过 POST 设置 updateCount。 该字段在内部使用,也在内部更改。它也应该是内部可更新的。 GET 响应应包含此字段,但最初不应通过 POST.

设置

@JsonCreator 告诉Jackson 使用这个构造函数来实例化一个对象。在此示例中,updateCount 不是构造函数参数之一,因此即使 POSTPUT 请求 JSON 主体包含一个名为 [=14] 的 属性 =], JSON 属性 updateCount in JSON body 被忽略。正如您在构造函数中看到的,Foo.updateCount 由代码初始化。

A getter getUpdateCount with @JsonProperty 使字段 updateCount 可序列化,即包含在 GET 请求的响应正文中。

A setter setUpdateCount with @JsonIgnore 使字段 updateCount 不可反序列化,在 PATCH 更新请求中被忽略。

我建议您删除 setter setUpdateCount,并使用方法 incrementUpdateCount 来递增。

public class Foo{

    @Id
    private String id;

    private String name;

    private int updateCount;

    @JsonCreator
    public Foo(@JsonProperty("name") String name) {

        this.name = name;
        this.updateCount = 0;
    }

    // getter and setter of name is omitted for briefness

    @JsonProperty
    public int getUpdateCount() {
        return updateCount;
    }

    @JsonIgnore
    public void setUpdateCount(int updateCount) {
        this.updateCount = updateCount;
    }

    public void incrementUpdateCount(int change) {
        this.updateCount += change;
    }

    public void incrementUpdateCount() {
        this.updateCount += 1;
    }
}

禁用 Jackson 映射器功能 INFER_PROPERTY_MUTATORS,方法是添加到您的 application.properties

spring.jackson.mapper.infer-property-mutators = false

application.yml 如果您使用 YAML 格式

spring:
  jackson:
    mapper:
      infer-property-mutators: false

如果启用了 Jackson 映射器功能 INFER_PROPERTY_MUTATORS,则 getter 表示一个字段是可反序列化的。 我有一个 test case 来显示启用和禁用此功能之间的区别。

注释 @JsonProperty(access = JsonProperty.Access.READ_ONLY) 有效。

public class Foo{

    @Id
    private String id;


    @JsonProperty(access = JsonProperty.Access.READ_ONLY) 
    private int updateCount;
    //getter setter

}