I want to exclude certain fields from a POST to my repositories.
For example I want to set the version myself so users cannot set this field themselves.
For example in the class below.
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@CreatedDate
private LocalDateTime created;
@LastModifiedDate
private LocalDateTime lastModified;
private String name;
}
I have tried to use the @ReadOnlyProperty
annotation and not having a setter for the version field. But nothing worked, users can still set the version fields themselves. I have also tried to implement a global initializer like below, but without success. The binder gets picked up though.
@ControllerAdvice
public class GlobalInitializer {
@InitBinder
public void globalBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("name");
}
}
You should place @JsonIgnore on field and on setter, and place @JsonProperty("propertyName") on getter.
Just tested - works for me: