Currently I am using mongodb with java. I don't want to reopen my connection to the datastore every time, so I thought I should make a static variable:
package Config;
import java.net.UnknownHostException;
import com.google.code.morphia.*;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class Config {
static String dbUrl = "url";
static int dbPort = portnumber;
static String username = "user";
static String password = "pw";
static String dbName = "dbname";
public static Datastore ds;
public static Datastore getDatastore() throws UnknownHostException,
MongoException {
if (ds == null) {
ds = connect();
}
return ds;
}
public static Datastore connect() throws UnknownHostException,
MongoException {
Mongo m = new Mongo(dbUrl, dbPort);
Datastore ds = new Morphia().createDatastore(m, dbName);
boolean con = ds.getDB().authenticate(username, password.toCharArray());// todo
return ds;
}
}
I would use it like this:
Config.getDatastore().doSomthing();
Beside those un-handled exceptions, is this the correct way of using a static
variable?