在 java 中将数据存储到 mongodb

store data into mongodb in java

我解析文件并检索其中包含的内容,然后尝试使用吗啡将它们存储在我的数据库中,但出现此错误:

INFO: LoggerImplFactory set to org.mongodb.morphia.logging.jdk.JDKLoggerFactory
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/client/model/geojson/codecs/GeoJsonCodecProvider

这是我的主要内容:

finally {


                    Morphia morphia =new Morphia(); 
                    String mongo2 ="test";
                    CelluDAO cellDAO=new CelluDAO(MongoUtil.getMongo(),morphia,mongo2);
                    System.out.println("Connect to database successfully");

                    for (Cellu cel : data) {
                        System.out.println(cel.getT());
                        cellDAO.save(cel);
                    }


                     MongoUtil.getMongo().close();
                } 

这是我的 class CelluDAO :

public class CelluDAO extends BasicDAO<Cellu,String> {

    public CelluDAO (MongoClient mongoClient, Morphia morphia, String dbName) {
        super(mongoClient, morphia, dbName);
    }

public List<Cellu> findAll() {
    return ds.find(Cellu.class).asList();

}
public List<Cellu> findUnderID(int id){
    return ds.find(Cellu.class).filter("Id",id).order("Id").asList();
}

}

我的 class Mongoutil:

public class MongoUtil {
        private static final int port = 27017;
        private static final String host = "localhost";
        private static final String databaseName = "test";

        private static MongoClient mongo = null;
        private static MongoDatabase db = null;

        public static MongoClient getMongo() {
            if (mongo == null) {
                mongo = new MongoClient(host, port);
            }
            return mongo;
        }

        public static MongoDatabase getDB() {
            if (db == null) {
                if (mongo == null) {
                    mongo = getMongo();
                }
                db = mongo.getDatabase(databaseName);
            }
            return db;
        }

        public MongoCollection<Document> getCollection(String collection) {
            if (db == null) {
                db = getDB();
            }
            MongoCollection<Document> table = db.getCollection(collection);
            return table;
        }

    }

我做事正确吗? 有没有更好的方法呢?

确保您使用的是 Java 驱动程序的 3.x 行中的内容。听起来您使用的是 2.13 或 2.14。

Java https://docs.oracle.com/javase/7/docs/api/java/lang/NoClassDefFoundError.html 处的 NoClassDefFoundError 文档如下。

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

首先确保MongoDB和Driver的版本相同。

尝试使用 MongoDB Java 驱动程序版本 3.1 或更高版本。我在 MongoDB Java 文档中看到 com.mongodb.client.model.geojson.codecs 包 -http://api.mongodb.org/java/3.1, where as this is not available with version 3.0 - http://api.mongodb.org/java/3.0

因此 Java 驱动程序可能会针对您正在使用的版本(即 3.0.4)抛出错误。