65 lines
1.8 KiB
Java
65 lines
1.8 KiB
Java
package eu.univento.commons.database;
|
|
|
|
import com.mongodb.MongoClient;
|
|
import com.mongodb.MongoCredential;
|
|
import com.mongodb.ServerAddress;
|
|
import com.mongodb.client.MongoDatabase;
|
|
import lombok.Getter;
|
|
import org.mongodb.morphia.Datastore;
|
|
import org.mongodb.morphia.Morphia;
|
|
|
|
import java.util.Collections;
|
|
|
|
/**
|
|
* @author joethei
|
|
* @version 1.0
|
|
*/
|
|
public class MongoDB {
|
|
|
|
private final MongoClient client;
|
|
@Getter private final Datastore datastore;
|
|
private MongoDatabase database;
|
|
|
|
private final String host;
|
|
private final int port;
|
|
private final String username;
|
|
private final String password;
|
|
private final String databaseName;
|
|
|
|
public MongoDB(String host, int port, String username, String password, String databaseName) {
|
|
this.host = host;
|
|
this.port = port;
|
|
this.username = username;
|
|
this.password = password;
|
|
this.databaseName = databaseName;
|
|
|
|
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
|
|
client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(credential));
|
|
|
|
Morphia morphia = new Morphia();
|
|
morphia.mapPackage("eu.univento.commons.player");
|
|
|
|
datastore = morphia.createDatastore(client, "univento");
|
|
datastore.ensureIndexes();
|
|
}
|
|
|
|
private MongoClient getClient() {
|
|
if(client == null)
|
|
new MongoDB(host, port, username, password, databaseName);
|
|
return client;
|
|
}
|
|
|
|
public MongoDatabase getDatabase() {
|
|
if(database == null)
|
|
database = getClient().getDatabase(databaseName);
|
|
return database;
|
|
}
|
|
public void setDatabase(String database) {
|
|
this.database = getClient().getDatabase(database);
|
|
}
|
|
|
|
void closeConnection() {
|
|
if(client != null)
|
|
client.close();
|
|
}
|
|
} |