Im new on Play framework and i've started a project with it specially the version 2.8.8. I'm using mongoDB for my project and eclipse for play. now now i'm trying to connect my database with play. I read a lot of things about Ebean which is play ORM for database connection i've try it but i still not handle my problem. my goal is to connect to my database made a request that will register information in the collection(mongo)
can somebody show me what to do how it works? I need some useful tips configuration or sample model to view so that i can moving forward on my project.
You need to include these dependencies in your build.sbt for interacting with mongo. (you can use your relevant versions. the below-given versions are being used with play 2.7)
"org.jongo" % "jongo" % "1.3.1", "org.mongodb" % "mongo-java-driver" % "3.10.2"
Mongo Repository(Connector/Dao) class example:-
import handlers.MongoConnectionHandler;
import com.mongodb.BasicDBObject;
import com.mongodb.WriteResult;
import models.mongo.Message;
import org.jongo.MongoCollection;
import org.jongo.MongoCursor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import skeletons.requests.ChatHistoryRequest;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
@Singleton
public class MessageMongoRepository {
private final MongoCollection messageCollection;
@Inject
public MessageMongoRepository(MongoConnectionHandler mongoConnectionHandler) {
messageCollection = mongoConnectionHandler.getCollection("messages");
}
public List<Message> fetchRecords() {
BasicDBObject query = new BasicDBObject();
query.put("f1", "val 1");
query.put("f2", "val2");
query.put("f3","val 3" );
BasicDBObject sort = new BasicDBObject();
MongoCursor<Message> messages = null;
List<Message> messageList = new ArrayList<>();
try {
messages = messageCollection.find(query.toString()).sort(sort.toString()).limit(request.getSize()).as(Message.class);
} catch (Exception e) {
logger.error("Error in fetching messages");
throw e;
}
if (messages != null) {
while (messages.hasNext()) {
messageList.add(messages.next());
}
} else {
logger.error("No messages");
}
return messageList;
}
public String saveRecord(Message rec) {
WriteResult result;
try {
result = messageCollection.save(rec);
} catch (Exception e) {
throw e;
}
return result.getUpsertedId().toString();
}
}
The message is a User Defined Java Class
MongoConnectionHandler Example
import com.mongodb.*;
import com.typesafe.config.Config;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
public class MongoConnectionHandler {
private final Config config;
private final DB db;
private final Jongo jongo;
private final MongoClient mongoClient;
private static final MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder()
.connectTimeout(1000)
.maxConnectionIdleTime(1000)
.socketTimeout(1000)
.maxWaitTime(1000)
.build();
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Inject
public MongoConnectionHandler(Config config) {
this.config = config;
String user = this.config.getString("mongo.auth.user");
String pass = this.config.getString("mongo.auth.pass");
String authDb = this.config.getString("mongo.auth.db");
MongoCredential mongoCredential = MongoCredential.createCredential(user, authDb, pass.toCharArray());
List<ServerAddress> serverAddressList = new ArrayList<>();
String[] hostList = this.config.getString("mongo.host").split(",");
for (String host : hostList) {
String[] ipPortPair = host.split(":");
ServerAddress serverAddress = new ServerAddress(ipPortPair[0], Integer.valueOf(ipPortPair[1]));
serverAddressList.add(serverAddress);
}
mongoClient = new MongoClient(serverAddressList, mongoCredential, mongoClientOptions);
db = mongoClient.getDB(this.config.getString("mongo.db"));
jongo = new Jongo(db);
}
public MongoCollection getCollection(String name) {
MongoCollection collection = null;
try {
collection = jongo.getCollection(name);
} catch (Exception e) {
logger.error("Error while getting collection : {}", name);
throw e;
}
return collection;
}
}
heres how you get mongodb and play framework to co-operate the understanding of modules in play will be necessary check out this module follow the steps and you get mongodb working with play https://github.com/morellik/play-morphia
(please mark correct if this answer helps,i was stuck here recently)
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.