I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:
Error :
Exception in t
Pro
you continue to work with strong typed objects as you wanted to
Contra
Some people really dislike : extends
package foo;
import com.mongodb.BasicDBObject;
public class Employee extends BasicDBObject {
private static final long serialVersionUID = 2105061907470199595L;
//should be something shorter as "name" like "n"
//here just use name to conform your sample
public static final String NAME = "name";
public static final String NO = "no";
public static final String COLLECTION_NAME = "employee";
public Long getNo() {
return getLong(NO);
}
public void setNo(long no) {
put(NO, no);
}
public String getName() {
return getString(NAME);
}
public void setName(String name) {
put(NAME, name);
}
}
package foo;
import java.net.UnknownHostException;
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("yeahMongo");
Employee employee = new Employee();
employee.setNo(1L);
employee.setName("yogesh");
DBCollection employeeCollection = null ;
employeeCollection = db.getCollection(Employee.COLLECTION_NAME);
employeeCollection.save(employee);
System.err.println(employeeCollection.findOne());
}
}
In addition to morphia you should take a look to jongo : http://jongo.org/ jongo use the same form syntax as js mongo engine, and I found it great point for a beginner. You don't have to switch your mental map between mongojs and java. you can use the js sample with little changes.