Connect java project to mongodb database

拟墨画扇 提交于 2020-01-25 06:44:14

问题


I'm trying to connect java project to my mongodb database. But I keep recieving this error although I imported the mongodb driver to the project:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/internal/connection/ServerAddressHelper

and that's my connection code:

MongoClient mongoClient = new MongoClient(new 
MongoClientURI("mongodb://localhost:27017"));
MongoDatabase database = mongoClient.getDatabase("Etudiant");
MongoCollection collection = database.getCollection("EtudiantC");
System.out.println("connected!");

回答1:


The NoClassDefFoundError exception tells you that the class was there when the code you run was compiled, but it is missing in your application's classpath now.

The most probable explanation is that you did add the mongodb-driver.jar to your classpath, but forgot about adding its transitive dependencies as well. The reported missing class ServerAddressHelper is present inside the mongodb-driver-core.jar.

So how to solve this problem? Either use a dependency management system like Maven or Gradle for automatically downloading all the necessary jar-s, or you need to do this by other means (e. g. manually). It seems like you may also use the all-in-one mongo-java-driver.jar instead - see project's official documentation for details (search for "Binaries" on the page).



来源:https://stackoverflow.com/questions/58882789/connect-java-project-to-mongodb-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!