java - 将 Java 对象插入 MongoDB,并将日期值作为字符串插入
问题描述
我有以下带有 Java 的 mongoDB 代码,我正在尝试将 TechnologyDetails 插入 mongoDB,并在映射器方法中设置所有值并持久保存到 DB。问题是因为 collection.insertOne() 仅将文档作为参数,在我将 TechnologyDetails pojo 转换为 Document 之后,在插入到 MongoDB 期间,“createdAt”日期数据类型字段作为字符串插入到 DB。任何人都可以帮助解决这个问题,即使在将 pojo 转换为 Document 之后如何保持相同的数据类型。所以我将日期作为日期插入到 mongoDb。谢谢。
final FindIterable<Document> iterable = technologiesCollection
.find(and(eq(APPLICATION, techKey.getApplication()), eq(VERSION, techKey.getVersion()),
eq(TECHNOLOGY, techKey.getTechnology())));
final Document document = iterable.first();
final ObjectMapper mapper = new ObjectMapper();
final TechnologyDetails technology = mapper.convertValue(document, TechnologyDetails.class);
if (technology == null) {
//mapper method to set the technology fields
Document tech = mapper(techKey, hosts);
try {
technologiesCollection.insertOne(tech);
} catch (Exception e) {
LOGGER.error("error", e);
}
}
private Document mapper(final TechnologyKey techKey, final Set<ApplicationHost> hosts) {
final TechnologyDetails technology = new TechnologyDetails();
final TransactionDetail txnDetail = new TransactionDetail();
final UserDetail userDetail = new UserDetail();
technology.setApplication(techKey.getApplication());
technology.setVersion(techKey.getVersion());
technology.setTechnology(techKey.getTechnology());
if (hosts != null) {
technology.setApplicationHosts(hosts);
}
userDetail.setDsid("123");
userDetail.setName("APP");
txnDetail.setCreatedBy(userDetail);
final Date date = new Date(System.currentTimeMillis());
txnDetail.setCreatedAt(date);
technology.setTxnDetails(txnDetail);
Document document = Document.parse(new JSONObject(technology).toString());
return document;
}
解决方案
我建议使用 ODM
推荐阅读
- flutter - Flutter:InkWell 在 Card 中完全不起作用
- python - 如何在 mac os x 上使用 gunicorn 和 python3.8 而不是 python3.9?
- javascript - 如何在 React 中使用 Toggle 方法切换 CSS 样式
- google-classroom - 获取学生提交的 google 课堂作业的 id
- sql - 使用分隔符连接或合并许多列值并忽略空值 - SQL Server 2016 或更早版本
- python - TypeError:文件必须具有“写入”属性
- javascript - 如何从 React 中的 API 数据制作 3 列行
- javascript - 来自 json feed 的 diplsay 状态数据,并在 html 表的 td 字段上显示每个结果
- java - Drools 函数访问
- git - Github问题:Git推送到master分支,不是main,不能合并两者