Insert DBObject into MongoDB using Spring Data

I tried to insert the following DBObject into MongoDB using Spring Data:

BasicDBObject document = new BasicDBObject(); document.put("country", "us"); document.put("city", "NY"); mongoTemplate.insert(document); 

where mongoTemplate is my Spring template (org.springframework.data.mongodb.core.MongoTemplate).

On execution, I get:

 Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: No Persitent Entity information found for the class com.mongodb.BasicDBObject at org.springframework.data.mongodb.core.MongoTemplate.determineCollectionName(MongoTemplate.java:1747) at org.springframework.data.mongodb.core.MongoTemplate.determineEntityCollectionName(MongoTemplate.java:1732) at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:658) 

My JSON will be dynamic at the end. So, any idea how to provide this entity information dynamically? Or is there another way to embed source JSON in Mongodb through Spring Data?

+7
spring-data-mongodb mongodb
source share
2 answers

You are misleading spring-data with the normal preservation of mangoes using the java driver.

If you want to transfer data to mongoDB directly using the java driver, you should use BasicDBObject, as you showed, except that you will not use the mongoTemaplate class to save, but rather the MongoClient class. So it will look like this:

 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); DB db = mongoClient.getDB( "mydb" ); BasicDBObject o = new BasicDBObject(); o.set...... coll.insert(o); 

But if you are trying to save the document using spring-data, you need to create a java class to represent your document (for example: Person) and annotate this class with @Document (collection = "person") and then use mongoTemplate (which is the spring class -data to save this object This is very similar to using JPA / hibernate.

So, it will look something like this.

 @Document(collection="person") public class Person { private String fisrtName; .... Relevant getters and setters } 

And then perseverance

 Person p = new Person(); p.setFirstName("foo"); p.setLastName("bar"); .... mongoTemplate.save(p); 
+10
source share

Another way to do this is to directly access the DBCollection object using MongoTemplate :

 DBObject company = new BasicDBObject(); ... DBCollection collection = mongoTemplate.getCollection("company"); collection.insert(company); 
+2
source share

All Articles