0

I recently started messing with Java and MongoDB and found out that things are not as straight forward as in C#.

In C# i could make a class (as a model) to save it as a Bson Object in MongoDB with the following line.

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

In Java I made my i am getting the class like this:

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

When I am trying to insert this Bson object i populate it like this

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);

}

Very similar to the way I was doing it in C# but in Java I get this error:

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

From my understanding I need POJO codec to achieve the same functionality is this correct? If yes how can I create it?

Thank you in advance!

  • Possible duplicate of [MongoDB Java Inserting Throws org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class io.github.ilkgunel.mongodb.Pojo](https://stackoverflow.com/questions/39433775/mongodb-java-inserting-throws-org-bson-codecs-configuration-codecconfigurationex) – deHaar Nov 26 '18 at 13:07

1 Answers1

1

By configuring a CodecRegistry, it will manage the BSON->POJO for you;

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);  

You also need to statically import org.bson.codecs.configuration.CodecRegistries.fromRegistries and org.bson.codecs.configuration.CodecRegistries.fromProviders

There's a few examples on their github (hopefully it won't go down, lol): 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/

zuckerburg
  • 338
  • 2
  • 6