Java 当我试图查找不存在的文档时,我的代码引发异常
我的代码引发此异常:线程“AWT-EventQueue-0”java.lang.NullPointerException中的异常 当我输入mongodb在数据库中找不到的用户名或密码时,它会抛出异常,我尝试用多种方法调试它,但找不到引发异常的语句 问题是,当数据库中的用户名或密码不匹配时,我想向用户显示一条消息Java 当我试图查找不存在的文档时,我的代码引发异常,java,mongodb,Java,Mongodb,我的代码引发此异常:线程“AWT-EventQueue-0”java.lang.NullPointerException中的异常 当我输入mongodb在数据库中找不到的用户名或密码时,它会抛出异常,我尝试用多种方法调试它,但找不到引发异常的语句 问题是,当数据库中的用户名或密码不匹配时,我想向用户显示一条消息 public class GetEmployee { MongoClient mongoClient = MongoClients.create(); MongoDatabase db
public class GetEmployee {
MongoClient mongoClient = MongoClients.create();
MongoDatabase db = mongoClient.getDatabase("MirandasShoes");
MongoCollection<Document> collection = db.getCollection("Employees");
public Employee getEmployee(String username, String password) {
FindIterable<Document> findIterable = collection.find(new Document("Username", username).append("Password", password));
MongoCursor<Document> cursor = findIterable.iterator();
Employee e = new Employee();
if (cursor.hasNext()) {
Document doc = cursor.next();
//ArrayList<Object> o = new ArrayList<>(doc.values());
e.setId(doc.get("_id").toString());
e.setName(doc.get("Name").toString());
e.setAddress(doc.get("Address").toString());
e.setEmail(doc.get("Email").toString());
e.setPhone(doc.get("Phone").toString());
e.setUsername(doc.get("Username").toString());
e.setPassword(doc.get("Password").toString());
}
return e;//Get the shoes
}
public类GetEmployee{
MongoClient MongoClient=MongoClients.create();
MongoDatabase db=mongoClient.getDatabase(“MirandasShoes”);
MongoCollection collection=db.getCollection(“员工”);
公共雇员getEmployee(字符串用户名、字符串密码){
FindIterable FindIterable=collection.find(新文档(“用户名”,用户名)。append(“密码”,密码));
MongoCursor=FindItemerable.iterator();
员工e=新员工();
if(cursor.hasNext()){
Document doc=cursor.next();
//ArrayList o=新的ArrayList(doc.values());
e、 setId(doc.get(“_id”).toString();
e、 setName(doc.get(“Name”).toString());
e、 setAddress(doc.get(“Address”).toString());
e、 setEmail(doc.get(“Email”).toString());
e、 setPhone(doc.get(“Phone”).toString());
e、 setUsername(doc.get(“Username”).toString());
e、 setPassword(doc.get(“Password”).toString());
}
return e;//取鞋
}
}我猜您的
集合.find()
调用将返回null,因此当您调用MongoCursor=findIterable.iterator()时代码>,FindItemerable实际上为null,不会有迭代器()方法
尝试在您的collection.find()
代码行之后检查if(findIterable)
。在哪一行有NPE?第一行显示:at UI.Login.btnLoginActionPerformed(Login.java:99)但它指的是我调用方法的文件,我添加了if语句并检查它是否为null,但它仍然抛出异常,你说“如果它不是null,则检查”。。。你的意思是你的代码是if(findIterable!==null){}
还是你做了if(findIterable){}
?我做了if(findIterable!=null)
,因为当我做if(findIterable)
时,它说它不能转换成布尔对不起,我错过了“java”标签,想到了“javascript”,这是我更熟悉的驱动程序,而不是java驱动程序。我仍然怀疑find方法是问题的根源,也许它与查询有关?我偶然发现了这一页:。下面是一些关于为find方法生成查询参数的示例。也许这会指引你走向正确的方向。