将Java项目连接到mongodb数据库 [英] Connect java project to mongodb database

查看:1000
本文介绍了将Java项目连接到mongodb数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Java项目连接到我的mongodb数据库。但是尽管我将mongodb驱动程序导入到项目中,但我仍然收到此错误:



线程 main中的异常java.lang.NoClassDefFoundError:com / mongodb / internal / connection / ServerAddressHelper



这就是我的连接代码:

  MongoClient mongoClient =新的MongoClient(新的
MongoClientURI( mongodb:// localhost:27017));
MongoDatabase数据库= mongoClient.getDatabase( Etudiant);
MongoCollection集合= database.getCollection( EtudiantC);
System.out.println( connected!);


解决方案

NoClassDefFoundError 异常告诉您,编译运行的代码时该类在那里,但是在应用程序的类路径



最可能的解释是您确实添加了 mongodb-driver.jar 到您的类路径,但是忘记了添加其传递依赖项作为好。报告的缺少类 ServerAddressHelper 位于 mongodb-driver-core.jar 中。



<那么如何解决这个问题呢?请使用Maven或Gradle之类的依赖项管理系统来自动下载所有必需的jar,或者您需要通过其他方式(例如手动)执行此操作。似乎您也可以使用多合一的 mongo-java-driver.jar -请参阅项目的官方文档以获取详细信息(在页面上搜索二进制文件)。


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

解决方案

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

这篇关于将Java项目连接到mongodb数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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