Monday, 18 November 2019

springboot mongo, auto add createdDate and lastModifyDate on your table (collection)

You actually don't need manually add timestamp and update them programtically for your mongo collections.

You can just add below 4 lines into your POJO:

@LastModifiedDate
private Instant lastModifiedDate;
@CreatedDate

private Instant createdDate;

and then add below line to your application:



@EnableMongoAuditing


the database will manage it for you.

https://codeboje.de/spring-data-auditing/


however if you give ID when you are creating a new document, then the database will consider you are updating, so you will never get "createDate"

https://jira.spring.io/browse/DATAMONGO-946

as above link mentioned, you have 2 workaround, i suggest you use @version. you just need to add below to your POJO:


@Version

private String version;


Next, you need to make sure you copy them over when you update them otherwise you may lost them.


No comments:

Post a comment