[英]java mongo create date
I have a java code that is inserting an object into a collection in Mongo DB. 我有一个Java代码,它将对象插入Mongo DB中的集合中。 While I insert this new object (details of the object given below), I need to also insert a creation date. 当我插入这个新对象时(下面给出了该对象的详细信息),我还需要插入一个创建日期。 What's the best way to handle this? 处理此问题的最佳方法是什么? Since we have different time zones, I want to make sure that I am following the correct approach for saving and reading the date fields. 由于我们有不同的时区,因此我想确保使用正确的方法来保存和读取日期字段。
document structure: I need to have my java code create a system date that would insert the creation date into Mongo DB in a proper format. 文档结构:我需要让我的Java代码创建一个系统日期,该日期将以正确的格式将创建日期插入到Mongo DB中。
{ "_id" : ObjectId("568ac782e4b0fbb00e4f1e45"), "cat" : "Abc", "name" : "testName" } {“ _id”:ObjectId(“ 568ac782e4b0fbb00e4f1e45”),“ cat”:“ Abc”,“ name”:“ testName”}
Please advise. 请指教。
Another approach - use standard Spring Data MongoDB auditing feature (assuming, your project is Spring based). 另一种方法-使用标准的Spring Data MongoDB审核功能(假设您的项目基于Spring)。
spring-data-mongodb
dependency 添加spring-data-mongodb
依赖项 @EnableMongoAuditing
使用@EnableMongoAuditing
注释您的主类 LocalDate createdDate
将一个字段LocalDate createdDate
添加到mongoDb实体类中 @CreatedDate
使用@CreatedDate
注释此新字段 So, your main class will look like this: 因此,您的主类将如下所示:
@SpringBootApplication
@EnableMongoAuditing
public class SpringDataMongodbAuditingApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataMongodbAuditingApplication.class, args);
}
}
And your entity class will look like this: 您的实体类将如下所示:
@Document
public class Client {
@Id
private ObjectId id;
private String name;
@CreatedDate
private LocalDate createdDate;
// constructor, getters, setters and other methods here ...
}
Your repository interface has nothing special: 您的存储库界面没有什么特别的:
@Repository
public interface ClientRepository extends MongoRepository<Client, ObjectId> {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.