0

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");
    }
}
akash
  • 22,664
  • 11
  • 59
  • 87
Agraphie
  • 33
  • 2
  • 7
  • http://stackoverflow.com/questions/24766067/how-to-disallow-put-while-allowing-post-and-patch-in-spring-data-rest Refer to this post –  Sep 10 '15 at 15:55
  • Thanks, but this is not what I am asking. I don't want to not expose certain methods like PUT or DELETE, but to disallow the setting of certain exposed fields – Agraphie Sep 10 '15 at 16:24
  • A Jackson JSONView perhaps? – Neil McGuigan Sep 10 '15 at 19:47
  • That seems like a good idea, but I think one cannot annotate a Repository which is annotated with "RepositoryRestResource" also with "JsonView". So I would have to write a controller for each repository, but then I can just remove the field manually myself... – Agraphie Sep 10 '15 at 20:30

1 Answers1

1

You should place @JsonIgnore on field and on setter, and place @JsonProperty("propertyName") on getter.

Just tested - works for me:

@JsonIgnore
@LastModifiedDate
private LocalDate lastUpdated;

@JsonProperty("lastUpdated")
public LocalDate getLastUpdated() {
    return lastUpdated;
}

@JsonIgnore
public void setLastUpdated(LocalDate lastUpdated) {
    this.lastUpdated = lastUpdated;
}
Ilya Novoseltsev
  • 1,803
  • 13
  • 19
  • I have marked this answer as correct. The only required thing is the `@JsonIgnore` on the setter field, the other annotations depend on your requirements. Thank you! – Agraphie Sep 20 '15 at 12:07