Inserting Java Object to MongoDB Collection Using Java

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

    Use BasicDBObjectBuilder to convert your POJO to an instance of DBObject which a DBCollection can save:

    import com.mongodb.BasicDBObjectBuilder;
    import com.mongodb.DBObject;
    
    public class Employee {
        private long no;
        private String name;
    
        // Getters and Setters
    
        public DBObject toDBObject() {
            BasicDBObjectBuilder builder = BasicDBObjectBuilder
                    .start("no", no)
                    .append("name", name);
            return builder.get();
        }
    }
    

    In order to save, just call toDBObject() on POJO instance and provide it to collection:

    public class test {
    
        public static void main(String[] args) throws UnknownHostException,
                MongoException {
            ...
            DBCollection dbCollection = db.getCollection("NameColl");
    
            Employee employee = new Employee();
            employee.setNo(1L);
            employee.setName("yogesh");
    
            dbCollection.save(employee.toDBObject());
        }
    }
    

    Using this approach:

    • You don't need to manually create a DBObject every time
    • You don't need to mess up your POJO by extending Mongo classes (what if your POJO is already extending a class?)
    • You don't need a Json mapper [and its annotations on POJO fields]
    • You only have dependency to java-mongo-driver jar

提交回复
热议问题