使用Spring Data将DBObject插入MongoDB [英] Insert DBObject into MongoDB using Spring Data

查看:164
本文介绍了使用Spring Data将DBObject插入MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Spring Data将以下DBObject插入MongoDB:

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

其中mongoTemplate是我的Spring模板(org.springframework.data.mongodb.core.MongoTemplate).

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

执行时,我得到:

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)

我的JSON最后会是动态的.那么有什么想法可以动态地提供这些实体信息吗? 还是有另一种方法可以通过Spring Data将原始JSON插入Mongodb中?

My JSON would be dynamic at the end. So any idea how to provide these entity information dynamically ? Or is there another way to insert raw JSON into Mongodb through Spring Data ?

推荐答案

您正在使用Java驱动程序将spring-data与常规mongo持久性混淆.

You are confusing spring-data with normal mongo persistence using the java driver.

如果您想直接使用java驱动程序将数据持久化到mongoDB,则可以使用如上所示的BasicDBObject,只是不使用mongoTemaplate类来持久化,而使用MongoClient类来持久化.所以看起来像这样:

If you want to persist data to mongoDB directly using the java driver then you would use the BasicDBObject like you have shown except that you would not use the mongoTemaplate class to persist but rather the MongoClient class. So it would look like this:

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

但是,如果您尝试使用spring-data持久化文档,则需要创建一个Java类来表示您的文档(例如:Person),并使用@Document(collection ="person")对该类进行注释,然后使用mongoTemplate(这是特定于Spring数据的类,用于保留该实体.这与使用JPA/hibernate非常相似.

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

所以看起来像这样

@Document(collection="person")
public class Person {
    private String fisrtName;
    ....

    Relevant getters and setters

}

然后是持久性

Person p = new Person();
p.setFirstName("foo");
p.setLastName("bar");
....
mongoTemplate.save(p);

这篇关于使用Spring Data将DBObject插入MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆