jny
jny

Reputation: 8057

How can I prevent Spring Data Rest from from nulling out @CreatedDate during updates?

I am trying spring-data-rest with spring-data-mongo and a lot of things are working beautifully out of the box, including support for eTag field. @EnableMongoAuditing annotations works very well too: when a document is created, the @CreatedDate and @LastModifiedDate fields are set.

The problem is that the @CreatedDate field being set to null during updates. I found an unresolved issue Mongo Auditing: @CreatedDate field gets set to null on updates with Spring Data Rest with a suggested workaround of using the @JsonIgnore annotation which does not work for me.

There was also a similar question here which does not appear to be the same issue.

I am using version 1.10.1.RELEASE of spring-data-mongo and 2.6.1.Release of spring-data-rest.

Is there a solution to this issue?

Upvotes: 2

Views: 2066

Answers (2)

M. Justin
M. Justin

Reputation: 21074

One solution is to tell Jackson to output the field to JSON when serializing the object, but never read the value when deserializing the object, using the access element of JsonProperty:

@Document
public class MyDocument {
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @CreatedDate
    private Instant createdDate;
}

Spring Data REST will still output the createdDate field to JSON, but it will never read from it, including when performing an update.

Note that this will affect the serialization of your document class throughout the entire application. Often this will not be an issue, but it would pose a problem if there are other places in the code that need to be able to deserialize the createdDate from JSON.

Upvotes: 0

Maksim Kostromin
Maksim Kostromin

Reputation: 3778

Created date make sense only for immutable entities (which you are not going to update)

If entity is updatable, would like to use only last modified instead

For any other cases probably make sense use some history audition log..

  @Entity
  // ...
  public class MyEntity {
    // ... 
    @CreatedDate
    private LocalDateTime createdAt; // modifiedAt

    @PreUpdate
    public void fixSpringDataRestNullDate() {
      createdAt = LocalDateTime.now();
    }
  }

Upvotes: -2

Related Questions