如何从Spring-data-rest中选择PATCH操作中要更新的属性?

问题描述 投票:1回答:1

假设我有Person类:

class Person{ 
  private String id; 
  private String name; 
  private Date creationDate;
}

使用spring数据休息,我可以像这样修补此实体:

http://resourcehost/people/personId

带有json请求主体:

{
  "name":"Jon Smith",
  "creationDate":"2020-08-01 00:00:00"
}

我希望我的客户能够更新名称,但是我不希望消费者更新“ creationDate”字段。

如何配置是否应使用PATCH操作来更新属性?

我正在使用Spring Boot statrters版本2.2.2.RELEASE

spring-boot spring-data-rest spring-mongodb
1个回答
0
投票

您可以通过用PATCH对其进行注释,而忽略@JsonProperty(access = JsonProperty.Access.READ_ONLY)请求上对实体特定字段的更新,就像在下面的类中所做的一样。

@MappedSuperclass
public abstract class ModelBase implements Serializable {
    @Column(name = "creation_time")
    @CreatedDate
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private LocalDateTime creationTime;

    @Column(name = "modified_time")
    @LastModifiedDate
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private LocalDateTime modifiedTime;
}

Spring Data REST不会抛出异常,它只会忽略该字段。通过使用Projections,您应该可以忽略此行为。

© www.soinside.com 2019 - 2024. All rights reserved.