英文:
Problem with connecting to MongoDB on Java
问题
我在Java中使用MongoDB遇到了问题。我无法连接到数据库,总是收到异常并且无法解决。我使用了Maven依赖来实现。我尝试过使用其他版本的依赖。
我还确认了MongoDB是否在运行。我使用 *net start MongoDB* 命令启动了它。
我的代码:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class MongoDBTest {
public static void main(String[] args) throws Exception {
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://127.0.0.1:27017"));
}
}
我的依赖:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.0</version>
</dependency>
而我收到的异常信息:
Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.ConnectionString.getThreadsAllowedToBlockForConnectionMultiplier()Ljava/lang/Integer;
at com.mongodb.MongoClientURI.getOptions(MongoClientURI.java:351)
at com.mongodb.Mongo.createCluster(Mongo.java:724)
at com.mongodb.Mongo.<init>(Mongo.java:312)
at com.mongodb.Mongo.<init>(Mongo.java:308)
at com.mongodb.MongoClient.<init>(MongoClient.java:326)
at schlueting.arbeiten.MongoDBTest.main(MongoDBTest.java:9)
英文:
I have a problem with my MongoDB in Java. I cannot connect to it I always get an exception and could not resolve it. I use Maven Dependencies for that. I tried using other versions of the dependency.
I also checked that the MongoDB is running. I started it with net start MongoDB.
My code:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class MongoDBTest {
public static void main(String[] args) throws Exception {
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://127.0.0.1:27017"));
}
}
My dependency:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.0</version>
</dependency>
And the exception i got:
Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.ConnectionString.getThreadsAllowedToBlockForConnectionMultiplier()Ljava/lang/Integer;
at com.mongodb.MongoClientURI.getOptions(MongoClientURI.java:351)
at com.mongodb.Mongo.createCluster(Mongo.java:724)
at com.mongodb.Mongo.<init>(Mongo.java:312)
at com.mongodb.Mongo.<init>(Mongo.java:308)
at com.mongodb.MongoClient.<init>(MongoClient.java:326)
at schlueting.arbeiten.MongoDBTest.main(MongoDBTest.java:9)
答案1
得分: 2
解决方案是将以下内容添加到Maven依赖项中:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.10.1</version>
</dependency>
这解决了异常问题,我成功连接到了MavenDB。
顺便提一下,我当时使用的是MongoDB 4.4和JDK 11。
英文:
The solution was to add the following to the Maven dependencies:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.10.1</version>
</dependency>
That fixed the Exception and I could connect to the MavenDB.
Btw. I was using MongoDB 4.4 and JDK 11.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论