Inserting Java Object to MongoDB Collection Using Java

后端 未结 11 1263
情话喂你
情话喂你 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: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..

提交回复
热议问题