MongoDB的Java语法 [英] Java syntax with MongoDB
问题描述
我正在浏览MongoDB for java的介绍。有一些示例代码可以检索集合中的所有文档。代码有效,但我发现它有点......笨拙的缺乏一个更好的词。我想知道是否有一个特定的原因使它成为必要。给出的示例是:
I'm going through the intro to MongoDB for java. There's some example code to retrieve all the documents in a collection. The code works, but I find it a bit...clunky for lack of a better word. I'm wondering if there's a specific reason that makes it necessary. The given example is:
FindIterable<Document> iterable = db.getCollection("restaurants").find();
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
有什么理由 Block
实例有要在上面的例子中的 forEach
的每次迭代中创建?为什么不能更简单一些:
Is there some reason a Block
instance has to be created in every iteration of the forEach
in the above example? Why not something a little more straightforward like:
FindIterable<Document> iterable = db.getCollection("restaurants").find();
for (Document document : iterable) {
System.out.println(document);
}
推荐答案
虽然你当然可以使用你建议的表格:
While you can certainly use the form that you suggested:
for (Document document : col.find()) {
// do something
}
当for循环的主体抛出异常时会引入问题:如果这样发生光标不会被关闭。正确的习惯用法是明确使用MongoCursor(实现Closeable):
it introduces a problem when the body of the for loop throws an exception: if this happens the cursor will not be closed. The proper idiom to guard against that is to use MongoCursor (which implements Closeable) explicitly:
try (MongoCursor<Document> cursor = col.find().iterator()) {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
forEach方法只是一些语法糖避免需要应用程序代码担心必须像这样手动关闭光标。
The forEach method is just a bit of syntactic sugar to avoid the need for application code to worry about having to close the cursor manually like this.
如果你不想为每次迭代创建一个新的Block,你可以重构你的代码拉出匿名内部类创建,例如:
If you don't want to create a new Block for each iteration, you can refactor your code pull out the anonymous inner class creation, e.g.:
Block<Document> block = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
};
col.find().forEach(block);
当然,这甚至更笨拙,所以如果你能够使用Java 8,你可以取代整个带有lambda的东西:
Of course that's even clunkier, so if you are able to use Java 8, you can replace the whole thing with a lambda:
col.find().forEach((Block<Document>) document -> {
System.out.println(document);
});
或在这种情况下简单:
col.find().forEach((Block<Document>) System.out::println);
lambda metafactory 将确保不会创建不必要的对象。
The lambda metafactory will ensure that no unnecessary objects are created.
这篇关于MongoDB的Java语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!