【问题标题】:Read only properties for POST in spring data restSpring Data Rest 中 POST 的只读属性
【发布时间】:2020-10-15 14:50:33
【问题描述】:

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

我必须自己做吗?

例子是:

public class Foo{

@Id
private String id;

@ReadOnlyProperty
private int updateCount;

}

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

【问题讨论】:

    标签: spring-data-rest


    【解决方案1】:

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

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

    带有@JsonIgnore 的setter setUpdateCount 使字段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;
        }
    }
    

    通过添加到您的 application.properties 来禁用 Jackson 映射器功能 INFER_PROPERTY_MUTATORS

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

    application.yml,如果您使用 YAML 格式

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

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

    【讨论】:

    • 但是我有一些属性不应该通过 POST 设置或者应该被忽略
    • @SirWayne 问题 1:您的实体是如何创建的?由 HTTP POST 请求创建?由“新建”然后“保存”创建?还是实体(数据)已经存在于数据库中?
    • @SirWayne 问题 2:您的 POST 请求采取什么行动?创建还是更新?
    • 这是一个通过 POST 的新实体。我将添加一个示例 pojo
    • 所以我必须在自己的课程中混合 JPA 和 Jackson Annotation,对吧?
    【解决方案2】:

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

    public class Foo{
    
        @Id
        private String id;
    
    
        @JsonProperty(access = JsonProperty.Access.READ_ONLY) 
        private int updateCount;
        //getter setter
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-29
      • 2023-03-25
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      相关资源
      最近更新 更多