我如何将这个脚本从 C# 翻译成 Java

How would i translate this script from C# to Java

我最近开始弄乱 Java 和 MongoDB,发现事情不像在 C# 中那么简单。

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

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

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

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 编解码器来实现相同的功能,对吗?如果是,我该如何创建它?

提前致谢!

通过配置一个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 and here is the original link you also found: http://mongodb.github.io/mongo-java-driver/3.8/driver/getting-started/quick-start-pojo/