[英]Connect java project to mongodb database
I'm trying to connect java project to my mongodb database.我正在尝试将 java 项目连接到我的 mongodb 数据库。 But I keep recieving this error although I imported the mongodb driver to the project:
但是,尽管我将 mongodb 驱动程序导入到项目中,但我仍然收到此错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/internal/connection/ServerAddressHelper线程“主”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!");
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. NoClassDefFoundError
异常告诉您,当您运行的代码被编译时,class 就在那里,但现在您的应用程序的类路径中缺少它。
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.最可能的解释是您确实将mongodb-driver.jar添加到您的类路径中,但也忘记了添加其传递依赖项。 The reported missing class
ServerAddressHelper
is present inside the mongodb-driver-core.jar .报告的缺失 class
ServerAddressHelper
存在于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 (eg manually).
要么使用 Maven 或 Gradle 之类的依赖管理系统来自动下载所有必要的 jar-s,要么您需要通过其他方式(例如手动)执行此操作。 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).
看来您也可以改用一体机 mongo-java-driver.jar - 有关详细信息,请参阅项目的官方文档(在页面上搜索“二进制文件”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.