gpt4 book ai didi

Java MongoTemplate : Upserts Not Generating ObjectId

转载 作者:IT老高 更新时间:2023-10-28 13:29:47 26 4
gpt4 key购买 nike

我一直在开发一个使用 MongoDB 作为存储形式的 Java 应用程序,但是我遇到了一个问题。当用户在我的应用程序中添加评论时,它会将文档添加到评论集合中,然后对统计数据进行更新插入。但是, upsert 只添加第一次(更新或插入新数据后没有调用)。以下是相关代码:

public class CommentDAO implements ICommentDAO {

@Autowired
@Qualifier(value = "mongoDB")
MongoTemplate mongoTemplate;

public UserComment addComment(UserComment userComment) {
updateStats(userComment, 1L);
mongoTemplate.save(userComment);
return userComment;
}

public void updateStats(UserComment userComment, Long offset) {
Update update = new Update();
update.inc("total", offset);
Query query = query(where("entity").is(userComment.getEntity()));

WriteResult wr = mongoTemplate.upsert(query, update, CommentStat.class);
}
}

这是我的评论集合中的结果示例:

{ 
"_id" : ObjectId( "50ab0566e4b0ea8f74b82d48" ),
"_class" : "com.test.models.comment.UserComment",
"userId" : 4,
"ownerId" : 3,
"comment" : "Test comment",
"type" : "ART",
"entity" : "759446489112216656",
"date" : Date( 1353385318079 )
},
{
"_id" : ObjectId( "50ab0691e4b0775cf7daacad" ),
"_class" : "com.test.models.comment.UserComment",
"userId" : 4,
"ownerId" : 3,
"comment" : "Another test",
"type" : "ART",
"entity" : "759446489112216656",
"date" : Date( 1353385617619 )
}

...还有我单例、孤独的状态...

{ 
"entity" : "759446489112216656",
"total" : 1
}

请注意 stat 集合中缺少的“_id”和“_class”。我的 mongo 或 tomcat 日志中没有任何错误。有没有人遇到过这个问题或知道交易是什么?感谢您的帮助!

注意:如果我删除 upsert 并正常添加统计信息,一切都会增加(当然,这会为单个实体添加多个统计信息,这是不可取的)

最佳答案

我认为您可以尝试使用 @Document(collection = "colName") 注释您的类(class) - 我今天遇到了同样的问题。 Upserts 的工作有时真的很奇怪:我仍然无法找到始终如一地获取错误的方法。

实际上我所做的是创建了一个解决方法(临时的,只是“让它工作”),我必须检查对象中是否存在“_id”,如果它为空,我使用保存,如果不是 - 我使用更新。是的,这很奇怪,但确实有效。

关于Java MongoTemplate : Upserts Not Generating ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13466773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com