如何使用 Spring Data MongoDB 插入新日期? [英] How can I do a insert a new Date with Spring Data MongoDB?

查看:21
本文介绍了如何使用 Spring Data MongoDB 插入新日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Spring Data MongoDB 插入新日期?

How can I insert new Date with Spring Data MongoDB?

我目前正在诉诸

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()}) 

直接在 mongo shell 中.

diretly in the mongo shell.

如何使用 Sprint-Data-MongoDB 实现这一目标?

How can this be achieved with Sprint-Data-MongoDB?

推荐答案

您可以通过使用 spring-data 审计功能一致地实现这一点

you can achieve this consistently by using spring-data audit feature

为了启用审计,我们需要添加 <mongo:auditing/> 标记到 Spring 配置.

In order to enable auditing we need to add < mongo:auditing/ > tag to Spring configuration.

审计让您可以声明性地告诉 Spring 进行存储:

Auditing let you declaratively tell Spring to store:

  • 文档创建日期:@CreatedDate
  • 上次更新文档的日期:@LastModifiedDate
  • 创建文档的用户:@CreatedBy
  • 最近更新的用户:@LastModifiedBy
  • 当前文档版本:@Version

对于我们的用例,如果我们结合 javax.persistence jar 日期样式和 mongodb 审计,我们总是通过使用以下声明来获得 new ISODate()

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; 

这样你就可以使用 spring-data-mongodb 创建新的日期

This way you can create new Date using spring-data-mongodb

这篇关于如何使用 Spring Data MongoDB 插入新日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆