【问题标题】:Passing MongoDB ObjectId in Play Framework URL在 Play Framework URL 中传递 MongoDB ObjectId
【发布时间】:2012-12-28 17:23:14
【问题描述】:

您好,我正在使用 Java 学习 Play Framework 2,但遇到了问题。我使用 MongoDB,并有一个简单的类 User,其中 ObjectId 作为唯一 ID。

public class User {


    @JsonProperty
    public ObjectId id;

..

在我看来,我想添加一个按钮来删除当前用户,如下所示:

 @form(routes.Application.deleteUser(user.id)) {
       <input type="submit" value="Delete">
 }

在我的路线文件中:

POST    /users/:id/delete               controllers.Application.deleteUser(id: org.bson.types.ObjectId)

但现在我遇到了一个错误:

“未找到类型 org.bson.types.ObjectId 的 URL 路径绑定器。尝试为此类型实现隐式 PathBindable”

我尝试了很多东西,例如我尝试仅将 ObjectId 值作为字符串传递,但对我没有任何效果。谁能帮我解决这个问题?

【问题讨论】:

标签: java mongodb playframework playframework-2.0 objectid


【解决方案1】:

您可以使用具有必要绑定器的play-salat,只需将其作为依赖项添加到您的project/Build.scala 并将其导入您的路线和模板:

import sbt._
import Keys._
import PlayProject._

object ApplicationBuild extends Build {

  val appDependencies = Seq(
    "se.radley" %% "play-plugins-salat" % "1.2-SNAPSHOT"
  )

  val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings(
    resolvers       += "OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/",
    routesImport    += "se.radley.plugin.salat.Binders._",
    templatesImport += "org.bson.types.ObjectId"
  )
}

也可以看看这个example application

【讨论】:

  • 那很好,但我需要 Java 中的一些东西
  • 我知道,但仍然认为它对你有用。在 Java 应用程序中可以使用 Scala 库。
  • 我遇到了另一个问题。出现错误:[NullPointerException: null] on line : Call("POST", "/users/" + implicitly[PathBindable[ObjectId]].unbind("id", id) + "/delete")
  • 你确定你在这一行传递了id @form(routes.Application.deleteUser(user.id)) {吗?你能通过显示来检查吗?看起来您的 user 为空。
  • 这很奇怪。例如在 mongo 控制台中: > db.users.find() { "_id" : ObjectId("50d76439ba472c9cee2c5435"), "name" : "Franek" } { "_id" : ObjectId("50e0a25c4fbea3f0450d3690"), "name" : "Ziomek" } 但是当我想在应用程序中显示它时:@for(user @(user.id)
  • @(user.name)
  • }我只看到名字,没有 id!
【解决方案2】:

您可能正在寻找Morphia,Java 的MongoDB ORM,毕竟? 对于 Morphia,一个好的启动可能是 Slideshare 中的 this tutorial

顺便说一句,我发现 _id 用户名字符串更好地反对 Mongo 的 ObjectId。

小例子:

//Routes
GET     /add/:username     controllers.Application.createTestPerson(username)
GET    /delete/:username   controllers.Application.delete(username)

//Controller
public class Application extends Controller {
  ...
  public static Result createTestPerson(String username){
      //DB connection and Morphia Datastore
      DBConn conn = new DBConn("test");
      Datastore ds = conn.getDatastore();
      //Person document for saving
      Person person = new Person(username);
      person.setName("John", "Doe");
      //save person to Mongo
      ds.save(person);  
      return ok("user \""+username+"\" saved");
  }

  public static Result delete(String username){
      //DB connection and Morphia Datastore
      DBConn conn = new DBConn("test");
      Datastore ds = conn.getDatastore();
      ds.delete(Person.class,username);
      return ok("user \""+username+"\" deleted");
  }
}

//models Person.java
import com.google.code.morphia.annotations.*;
import org.bson.types.ObjectId;

@Entity("persons")
public class Person {

    @Id
    String userName;
    Name name;

    public Person(String u){ userName = u; }

    public void setName(String first, String last){
        name = new Name(first, last);
    }
}
@Embedded
class Name {
    String first, last;

    public Name(){ }
    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }
}


//models DBConn.java
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
import java.net.UnknownHostException;

public class DBConn implements AutoCloseable{
    Morphia morphia;
    Mongo mongo;
    Datastore ds;

    public DBConn(){
        new DBConn("test");
    }
    public DBConn(String collection){
        morphia = new Morphia();
        try {
            mongo = new Mongo();
        } catch (UnknownHostException ex) {
            System.out.println("[Error] MongoDB Error");
        }
        ds = morphia.createDatastore(mongo, collection);
        System.out.println("DB conn success ["+ ds.getDB().getName() + "]");
    }
    public Datastore getDatastore(){
        return ds;
    }
    public void close() throws Exception {
        mongo.close();
    }
}

所以

localhost:9000/delete/what-ever-here

localhost:9000/createTestPerson/what-ever-here

您应该能够管理 Mongo Collection 并在 Mongo 控制台中查看结果:

> db.persons.find()
{ "_id" : "johndoe", "className" : "models.Person", "name" : { "first" : "John",
 "last" : "Doe" } }
>

【讨论】:

  • 我正在尝试与 Jongo 合作,并且真的很想使用 ObjectId
  • 使用 morphia 将用户名替换为“@Id ObjectId id”
  • 使用 Java 玩 2.3.x。
【解决方案3】:

在您的 build.sbt 上使用 Java 播放 2.3.x

import play.PlayImport.PlayKeys._

name := "test"

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
  javaJdbc,
  cache,
  javaWs,
  filters,
  "org.mongodb" % "mongo-java-driver" % "3.0.1",
  "se.radley" %% "play-plugins-salat" % "1.5.0"
)

val main = Project("test", file(".")).enablePlugins(play.PlayJava).settings(
    routesImport += "se.radley.plugin.salat.Binders._"
)

在您的路线上,您可以通过以下方式使用它

controllers.Application.index(id: ObjectId)

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签