使用Mongodb Collection的静态引用(Use static reference to Mongodb Collection)

编程入门 行业动态 更新时间:2024-10-28 17:24:27
使用Mongodb Collection的静态引用(Use static reference to Mongodb Collection)

我正在使用Spring Data for Mongodb,有时我用这种方式使用java驱动程序:

DBCollection mycoll = mongoOperations.getCollection("mycoll");

使集合mycoll静态并通过Singleton实例化它是否有意义?

I'm using Spring Data for Mongodb and sometimes I use the java driver this way :

DBCollection mycoll = mongoOperations.getCollection("mycoll");

Does it make sense to make the collection mycoll static and instantiate it through a Singleton?

最满意答案

你不需要一个Singleton,如果你只有一个实例而你需要管理那个实例,你只需要一个Singleton,请参阅这篇文章 。 Java Mongo驱动程序的源代码显示MongoDB集合不是这种情况。 'getCollection`方法仅验证集合是否存在于collectionCache(散列映射)中并且不执行任何数据库操作,因此多次调用它的开销很小。 请参阅以下https://github.com/mongodb/mongo-java-driver中的相关代码段

/** * Gets a collection with a given name. * * @param name the name of the collection to return * @return the collection */ public DBCollection getCollection(final String name) { DBCollection collection = collectionCache.get(name); if (collection != null) { return collection; }

You do not need a Singleton for this, you only need a Singleton if you can only ever have one instance and you need to manage that instance, see this post. The source code of the Java Mongo driver shows this is not the case for MongoDB collections. The 'getCollection` method only verifies if the collection exists in the collectionCache (a hashmap) and does not perform any database operations, so the overhead of calling it multiple times is minimal. See below the relevant code snippet from https://github.com/mongodb/mongo-java-driver

/** * Gets a collection with a given name. * * @param name the name of the collection to return * @return the collection */ public DBCollection getCollection(final String name) { DBCollection collection = collectionCache.get(name); if (collection != null) { return collection; }

更多推荐

本文发布于:2023-08-06 14:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   Collection   Mongodb   static   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!