Inserting Java Object to MongoDB Collection Using Java

后端 未结 11 1058
情话喂你
情话喂你 2020-12-28 13:34

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

Error :

Exception in t         


        
相关标签:
11条回答
  • 2020-12-28 13:57

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

    0 讨论(0)
  • 2020-12-28 13:57

    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.

    0 讨论(0)
  • 2020-12-28 13:59
    DB db = mongoClient.getDB( "mydb" );
    
    coll = db.getCollection("testCollection");
    
    Employee emp = new Employee();
    emp.setId("1001");
    emp.setName("John Doe");
    
    //Converting a custom Class(Employee) to BasicDBObject
    Gson gson = new Gson();
    BasicDBObject obj = (BasicDBObject)JSON.parse(gson.toJson(emp));
    coll.insert(obj);
    findEmployee(new BasicDBObject("id","1001"));
    
    
    public static void findEmployee(BasicDBObject query){
    
        DBCursor cursor = coll.find(query);
    
        try {
           while(cursor.hasNext()) {
              DBObject dbobj = cursor.next();
            //Converting BasicDBObject to a custom Class(Employee)
              Employee emp = (new Gson()).fromJson(dbobj.toString(), Employee.class);
              System.out.println(emp.getName());
           }
        } finally {
           cursor.close();
        }
    
    }
    

    I thought that it would be useful to post code that did conversions both ways.
    Storing an Employee Object
    Finding and re-creating an employee Object
    Hope this is useful..

    0 讨论(0)
  • 2020-12-28 14:03

    With MongoDB you cannot insert your Java bean in the DB, but you have to remap them to MongoDB Object.

    In your case you have to do:

    BasicDBObject basicDBObject = new BasicDBObject();
    basicDBObject.put("no", employee.getNo());
    basicDBObject.put("name", employee.getName());
    
    0 讨论(0)
  • 2020-12-28 14:06

    I have the same error, when I try to insert a java BasicDBObject into a MongoDb Collection.

    My object is created from a Xml converted to Json.

    java.lang.IllegalArgumentException: can't serialize class net.sf.json.JSONNull
        at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:299)
        at org.bson.BasicBSONEncoder.putMap(BasicBSONEncoder.java:339)
        at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:261)
    

    This error is caused by empty tags in Xml; when I removed all empty tags, then I solved it.

    0 讨论(0)
提交回复
热议问题