【问题标题】:How would i translate this script from C# to Java我如何将这个脚本从 C# 翻译成 Java
【发布时间】:2018-11-26 13:04:34
【问题描述】:

我最近开始使用 Java 和 MongoDB,发现事情不像 C# 那样简单。

在 C# 中,我可以使用以下行创建一个类(作为模型)以将其保存为 MongoDB 中的 Bson 对象。

acc = db.GetCollection<AccountModel>("accounts");

在 Java 中,我得到了这样的类:

accs = db.getCollection("accounts", AccountModel.class);

当我尝试插入这个 Bson 对象时,我会像这样填充它

public void InsertPlayer(String username){

    Model_Account newAccount = new Model_Account();
    newAccount.Username = "username";
    newAccount.Password = "password";
    newAccount.Email = "email@hotmail.com";

    accounts.insertOne(newAccount);

}

与我在 C# 中的操作方式非常相似,但在 Java 中出现此错误:

Caused by:org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class AccountModel.

据我了解,我需要 POJO 编解码器来实现相同的功能,这是正确的吗?如果是,我该如何创建它?

提前谢谢你!

【问题讨论】:

标签: java c# mongodb codec bson


【解决方案1】:

通过配置一个CodecRegistry,它会为你管理BSON->POJO;

MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
        MongoClient mongoClient = new MongoClient(connectionString);
        CodecRegistry pojoCodecRegistry = org.bson.codecs.configuration.CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), org.bson.codecs.configuration.CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        MongoDatabase database = mongoClient.getDatabase("testdb").withCodecRegistry(pojoCodecRegistry);  

您还需要静态导入 org.bson.codecs.configuration.CodecRegistries.fromRegistries 和 org.bson.codecs.configuration.CodecRegistries.fromProviders

在他们的 github 上有一些示例(希望它不会失败,哈哈):https://github.com/mongodb/mongo-java-driver/blob/master/driver-sync/src/examples/tour/PojoQuickTour.java,这是您还找到的原始链接:http://mongodb.github.io/mongo-java-driver/3.8/driver/getting-started/quick-start-pojo/

【讨论】:

  • @zuckerburg 感谢您的回复。我已经看过文档的那部分,但我不知道如何使用它。可以举个例子吗?
  • @zuckerburg 感谢您抽出宝贵时间,这正是我想要的。
  • 很高兴能帮上忙!
猜你喜欢
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 2021-07-25
  • 2015-01-27
相关资源
最近更新 更多