Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

eclipse - java.lang.NoClassDefFoundError when using MongoDB driver

I am trying to connect to a MongoDB database hosted on mlab using the Java driver on a servlet.

import org.bson.Document; 
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoConnection {

    protected void connectToMongo(String loc){

        String dbName = "readings";
        String collection = "data";

        MongoClientURI uri = new MongoClientURI("mongodb://user:[email protected]:43109/readings");
        MongoClient client = new MongoClient(uri);
        MongoDatabase db = client.getDatabase(dbName);

        MongoCollection<Document> readings = db.getCollection(collection);

        Document doc = Document.parse(loc);

        readings.insertOne(doc);

        client.close();
    }
}

The problem is I am getting the following error: java.lang.NoClassDefFoundError: com/mongodb/MongoClientURI

I looked at one answer (How to resolve ClassNotFoundException: com.mongodb.connection.BufferProvider?) that highlighted to me that I need other jars, I have since downloaded them however I am still getting this error.

I am using Eclipse and adding the three jars to the build path, navigating through the menu by right clicking on the project then following Build Path -> Configure build path -> Java build path -> libraries -> add external JARs.

Is this the right way to do it? Is there something else I am supposed to do as well/instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have java.lang.NoClassDefFoundError - that means your class is missed during runtime (not during build/compile time). So you should open your "Run Configurations" dialog for the project (project context menu -> "Run As" -> "Run Configurations...") and make sure you have bson-xxx.jar, mongodb-driver-xxx.jar, and mongodb-driver-core-xxx.jar somehow listed in Classpath tab. And yes, like Xavier Bouclet said - if you run it under application server - this jars should be added to your server's classpath.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...