10

I have simple class named Signal. Class looks as follows:

public class Signal {
    private String id;
    private Date timestamp;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Date getTimestamp() {
        return timestamp;
    }
    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}

I am trying to insert signal in MongoDB (v3.4). I am using the following method to insert:

public boolean xyz(Signal signal) {
            try {
                DatabaseConnection databaseConnection =DatabaseConnection.getInstance();
                MongoClient mongoClient = databaseConnection.getMongoClient();
                MongoDatabase db = mongoClient.getDatabase("myDb"); 
                MongoCollection<Signal> collection = db.getCollection("myCollection", Signal.class);
                collection.insertOne(signal);

                return true;
            } catch (Exception e){
                logger.error("Error", e);
                return false;
            }

        }

I am getting the following exception:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class in.co.mysite.webapi.models.Signal.

I checked a similar question here but insertion code is different. I took the hint from answer and modified my method but it doesn't look clean. Modified method is as follows:

public boolean xyz(Signal signal) {
        try {
            DatabaseConnection databaseConnection =DatabaseConnection.getInstance();
            MongoClient mongoClient = databaseConnection.getMongoClient();
            MongoDatabase db = mongoClient.getDatabase("myDb"); 
            MongoCollection<Document> collection = db.getCollection("myCollection");

            Document doc = new Document();

            doc.put("id", signal.getId());
            doc.put("timestamp", signal.getTimestamp());
            doc.put("_id", new ObjectId().toString());

            collection.insertOne(doc);

            return true;
        } catch (Exception e){
            logger.error("Error", e);
            return false;
        }

    }
Darshan Puranik
  • 1,055
  • 3
  • 14
  • 36

4 Answers4

13

You need to configure a CodecRegistry which will manage the translation from bson to your pojos:

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

PS: You could statically import org.bson.codecs.configuration.CodecRegistries.fromRegistries and org.bson.codecs.configuration.CodecRegistries.fromProviders.

A full example could be found in github.
The Mongodb java driver documentation contains also an article about managing pojos (The link is for the 3.8.0 driver version).

Mehdi
  • 1,494
  • 5
  • 33
  • 53
3

Follow the quick start guide for POJO. You need to register the codec to make the translation of your POJOs (Plain Old Java Object) to/from BSON: http://mongodb.github.io/mongo-java-driver/3.7/driver/getting-started/quick-start-pojo/

Renato Oliveira
  • 494
  • 4
  • 10
3

Documentation: MongoDB Driver Quick Start - POJOs

After following the above document, if you are still getting error, then

you could be using a generic document inside your collection like

class DocStore {
  String docId:
  String docType;
  Object document; // this will cause the BSON cast to throw a codec error
  Map<String, Object> document; // this won't
}

And still, you would want to cast your document from POJO to Map

mkyong comes to rescue.

As for the fetch, it works as expected but you might want to cast from Map to your POJO as a post-processing step, we can find some good answers here

Hope it helps! ️

Mukundhan
  • 3,284
  • 23
  • 36
1

Have you annotated your Java class? Looks like you need a @Entity above your class and @Id above your ID field.

Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76
  • I purposely didnt annotate because "signal" is technically not an entity according to my architecture/logic. – Darshan Puranik Nov 09 '17 at 05:14
  • But your saving it with Morphia as an entity and it is the top level representation of a collection, so it is an entity in this context – Nic Cottrell Nov 09 '17 at 07:45