Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Java Object to MongoDB Collection Using Java

Tags:

java

mongodb

I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:

Error :

Exception in thread "main" java.lang.IllegalArgumentException: can't serialize class net.yogesh.test.Employee     at org.bson.BSONEncoder._putObjectField(BSONEncoder.java:185)     at org.bson.BSONEncoder.putObject(BSONEncoder.java:119)     at org.bson.BSONEncoder.putObject(BSONEncoder.java:65)     at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:176)     at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:134)     at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:129)     at com.mongodb.DBCollection.save(DBCollection.java:418)     at net.yogesh.test.test.main(test.java:31) 

Emplyoee.java (POJO)

package net.yogesh.test;  import java.io.Serializable;  public class Employee implements Serializable {      private static final long serialVersionUID = 1L;     private long no;     private String name;      public Employee() {     }      public long getNo() {         return no;     }      public void setNo(long no) {         this.no = no;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }  } 

Main Method Class (test.java)

package net.yogesh.test;  import java.net.UnknownHostException;  import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; import com.mongodb.MongoException;  public class test {      public static void main(String[] args) throws UnknownHostException,             MongoException {          Mongo mongo = new Mongo("localhost", 27017);         DB db = mongo.getDB("test");          Employee employee = new Employee();         employee.setNo(1L);         employee.setName("yogesh");           BasicDBObject basicDBObject = new BasicDBObject("Name", employee);          DBCollection dbCollection = db.getCollection("NameColl");          dbCollection.save(basicDBObject);         }  } 

Can anybody explain why I am getting this error?

like image 253
Yogesh Prajapati Avatar asked Apr 16 '12 07:04

Yogesh Prajapati


1 Answers

I'm a little confused as to know why you'd think this would work in the first place. The first thing you need to know is how to map your POJO to a MongoDB document. Currently, you're not telling the system(your code) how to do that.

You can either use a mapping library for this (Morphia comes to mind) or use ReflectionDBObject. Either solution allows you to map POJO to MongoDB document or MongoDB document to POJO(the former way is a lot more nicely than the latter).

like image 86
Remon van Vliet Avatar answered Sep 23 '22 19:09

Remon van Vliet