How can I insert new Date with Spring Data MongoDB?
I'm currently resorting to
User = new User();
user.setCreationDate(new Date());
mongoOperation.save(user);
to solve the problem, but the end result is that a user is saved with the current time of the server that is running the code, instead of the current time of the server that is running the database.
Since this code will run in several instances on several servers in parallel, and the servers might have slightly different times, I'd like to replicate the exact same behaviour I would get from doing a
db.users.insert({'creationDate': new ISODate()})
diretly in the mongo shell.
How can this be achieved with Sprint-Data-MongoDB?
you can achieve this consistently by using spring-data audit feature
In order to enable auditing we need to add < mongo:auditing/ > tag to Spring configuration.
Auditing let you declaratively tell Spring to store:
@CreatedDate
@LastModifiedDate
@CreatedBy
@LastModifiedBy
@Version
For our use case if we combine javax.persistence jar date style and mongodb auditing we get new ISODate() always by using the following declaration
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "M-")
@CreatedDate
private Date createdDate;
This way you can create new Date using spring-data-mongodb
@Column(updatable = false)
@CreationTimestamp
private LocalDateTime createdAt;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.