java连接mongodb数据库,将Java项目连接到mongodb数据库

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值