Play Framework 2.5如何添加mongoDB? [英] Play Framework 2.5 how to add mongoDB?

查看:129
本文介绍了Play Framework 2.5如何添加mongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Play Framework 2.5应用程序中添加MongoDB。


我们可以看到这个模块 here ,在PF的文档中。

如何在我的应用程序中添加此模块?
@MongoEntity非常有用,但它是为1. * PF app写的。

I want to add MongoDB in my Play Framework 2.5 Application.
We can see this module here, in the documentation of PF.
How can I add this module in my app?
The @MongoEntity is really helpfull,but it's writen for 1.* PF app.

有2.5 PF的MongoDB模块?

我尝试过的另一件事:为2. *添加play-mongo模块(通过louth)但是在我的build.sbt中添加它们是不可能的:
图片

There is a MongoDB module for 2.5 PF?
And an other thing I've tryed: add play-mongo module (by louth) for 2.* but in my build.sbt it's impossible to add them: image.

推荐答案

您是使用Scala还是Java?

Are you on Scala or Java?

对于Scala,请查看 ReactMongo

For Scala, look at ReactMongo

对于Java,我也没有遇到任何插件,所以我开始使用 Morphia 。这是我如何配置它

For Java, I didnt come across any plugins too, so I started using Morphia. Here's how I have configured it

将此添加到build.sbt

Add this to build.sbt

    "org.mongodb.morphia" % "morphia" % "1.2.1",

这个到application.conf

And this to application.conf

    mongodb {
      host="localhost"
      port=27017
      database="my_db"
    }

现在,你必须创建一个Singleton类,喜欢

Now, you have to create a Singleton class, something like

public class MongoConfig {

    private static Datastore datastore;

    public static Datastore datastore() {
        if (datastore == null) {
            initDatastore();
        }
        return datastore;
    }

    public static void initDatastore() {

        final Morphia morphia = new Morphia();

        // Tell Morphia where to find our models
        morphia.mapPackage("models");

        MongoClient mongoClient = new MongoClient(
            ConfigFactory.load().getString("mongodb.host"),
            ConfigFactory.load().getInt("mongodb.port"));

        datastore = morphia.createDatastore(
            mongoClient, ConfigFactory.load().getString("mongodb.database"));
    }

}

样本模型

@Entity(value = "users", noClassnameStored = true)
public class User {

    public String name;

    public void save() {
        datastore().save(this);
    }

    public User query() {
        return datastore()
            .createQuery(User.class)
            .get();   
    }

}

这应该对你有用。如果我遗漏了什么,请告诉我。祝好运! :)

This should work for you. Let me know if I missed anything. Good luck! :)

这篇关于Play Framework 2.5如何添加mongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆