简体   繁体   中英

How do I configure Morphia/MongoDB datasource in PlayFramework 2.5 (JAVA)

I am trying to learn the Play Framework 2.5 (JAVA) with the underlying database being MongoDB.

I am using Morphia for entity mapping.

Currently I have the mongoDB datasource configured in my java code as shown here:-

private static final String DATABASE = "Database";

private static final MongoClientURI mongoClientURI = new MongoClientURI("mongodb://localhost:27017");
private static final MongoClient mongoClient = new MongoClient(mongoClientURI);

private static final Morphia morphia = new Morphia();
private static final Datastore datastore;

private static final DemeanorDAO demeanorDAO;

static {
    morphia.mapPackage("models.entity");

    datastore = morphia.createDatastore(mongoClient, DATABASE);
    datastore.ensureIndexes();
}

How do I configure the mongoDB datasource within the conf/application.conf

Do I use the PlayMorphia module?

I have found these configuration properties:-

# configure mongodb host and port. Default value: 127.0.0.1:27017
morphia.db.seeds=127.0.0.1:27017
#
# configure mongodb authentication
# - username. Default value: empty
morphia.db.username=user
# - password. Default value: empty
morphia.db.password=pass
#
# configure database name. Default value: test
morphia.db.name=test

How does my Java code use these properties?

In which conf/application.conf section do I place these properties?

There are several questions in you question.

Do I use the PlayMorphia module?

No you don't have to if you don't need specific features it provides.

How does my Java code use these properties?

You need to inject the Configuration ( source ) class in the component where you want to use the configuration values.

For the connection to the database for example :

new MongoClientURI("mongodb://" + configuration.getString("morphia.db.seeds"));

I let you check the Configuration class to see what methods are available.

In which conf/application.conf section do I place these properties?

There is no order in this file. A good practice is to order you properties by domain and alphabetically.

Disclaimer : you should review the way you declare the connection to the database. Don't start it in a static way, declare the connection when your application starts .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM