SilkyFalcon

Generation

code to explanationWed, 23 Nov 2022

package net.neoscale.database; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.HashMap; import java.util.Map; /** * Represents a MongoDB database connector. */ public class Database { /** * The map of the cached collections. */ private final Map<String, MongoCollection<Document>> collectionCache = new HashMap<>(); /** * The host address of the database. */ private final String host; /** * The listening port of the database. */ private final int port; /** * The name of the database. */ private final String database; /** * The names of the collections we want to use. */ private final String[] collections; /** * The connected client for the database. */ private MongoClient client; /** * The cached database instance. */ private MongoDatabase databaseCache; /** * Initialize database. * * @param host database host * @param port database port * @param database database name * @param collections used database collections */ public Database(String host, int port, String database, String... collections) { this.host = host; this.port = port; this.database = database; this.collections = collections; } /** * Initialize the database connection. */ public void connect() { client = new MongoClient(host, port); // get the database by name databaseCache = client.getDatabase(database); // get and cache the collections for (String collection : collections) { collectionCache.put(collection, databaseCache.getCollection(collection)); } } /** * Close the connection of the database. */ public void disconnect() { client.close(); } /** * Get the cached database. * * @return cached database */ public MongoDatabase getDatabase() { return databaseCache; } /** * Get a collection from cache. * * @param name collection name * @return cached collection */ public MongoCollection<Document> getCollection(String name) { // get the collection from cache MongoCollection<Document> collection = collectionCache.get(name); if (collection != null) return collection; // fetch the collection from database collection = databaseCache.getCollection(name); // put the collection in the cache collectionCache.put(name, collection); return collection; } }

The code is a simple representation of the database connection and it's usage.

Questions about programming?Chat with your personal AI assistant