[英]How can I do a insert a new Date with Spring Data MongoDB?
How can I insert new Date with Spring Data MongoDB?如何使用 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.直接在 mongo shell 中。
How can this be achieved with Sprint-Data-MongoDB?如何使用 Sprint-Data-MongoDB 实现这一目标?
you can achieve this consistently by using spring-data audit feature 您可以使用spring-data审核功能来一致地实现
In order to enable auditing we need to add < mongo:auditing/ > tag to Spring configuration. 为了启用审核,我们需要在Spring配置中添加<mongo:auditing />标签。
Auditing let you declaratively tell Spring to store: 审核使您可以声明性地告诉Spring存储:
@CreatedDate
创建文档的日期: @CreatedDate
@LastModifiedDate
上次更新文档的日期: @LastModifiedDate
@CreatedBy
创建文档的用户: @CreatedBy
@LastModifiedBy
完成最近更新的用户: @LastModifiedBy
@Version
当前文档版本: @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 对于我们的用例,如果我们结合使用javax.persistence jar日期样式和mongodb审核,则始终通过使用以下声明来获取新的ISODate()
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "M-")
@CreatedDate
private Date createdDate;
This way you can create new Date using spring-data-mongodb 这样您可以使用spring-data-mongodb创建新的日期
@Column(updatable = false)
@CreationTimestamp
private LocalDateTime createdAt;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.