Java 在Play框架URL中传递MongoDB对象ID

Java 在Play框架URL中传递MongoDB对象ID,java,mongodb,playframework,playframework-2.0,objectid,Java,Mongodb,Playframework,Playframework 2.0,Objectid,大家好,我正在学习用Java玩框架2,但遇到了一个问题。我使用MongoDB,并且有一个简单的类用户,ObjectId是唯一的id public class User { @JsonProperty public ObjectId id; .. 在我看来,我想添加一个按钮来删除当前用户,如下所示: @form(routes.Application.deleteUser(user.id)) { <input type="submit" value="D

大家好,我正在学习用Java玩框架2,但遇到了一个问题。我使用MongoDB,并且有一个简单的类用户,ObjectId是唯一的id

public class User {


    @JsonProperty
    public ObjectId id;

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

 @form(routes.Application.deleteUser(user.id)) {
       <input type="submit" value="Delete">
 }
但现在我犯了一个错误:

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

我尝试了很多方法,例如,我尝试只将ObjectId值作为字符串传递,但没有任何效果。有人能帮我吗?

您可以使用一些必要的绑定,只需将其作为依赖项添加到您的
项目/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"
  )
}
还可以看看这个。

毕竟,您可能正在寻找MongoDB ORM for Java? 一个好的开始可能是在幻灯片

顺便说一句,我发现对于
\u 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收集并在Mongo控制台中查看结果:

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

对于使用Java的Play 2.3.x,在build.sbt上

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)

Scala中有绑定器,看一看,也许你可以用Java重写它,那会很棒,但我需要一些Java的东西,我知道,但我仍然认为它对你有用。在Java应用程序中使用Scala库是可以的。我遇到了另一个问题。第行:Call(“POST”、“/users/”+隐式[PathBindable[ObjectId]]出现错误:[NullPointerException:null]。取消绑定(“id”,id)+“/delete”)是否确实在此行
@form(routes.Application.deleteUser(user.id))中传递id{
?您可以通过显示它来检查吗?看起来您的
用户
为空。这是一件奇怪的事情。例如,在mongo控制台中:>db.users.find(){“\u id”:ObjectId(“50d76439ba472c9cee2c5435”),“name:“Franek”}{“\u id”:ObjectId(“50e0a25c4fbea3f0450d3690”),“name:“Ziomek”}但当我想在application:@for(user)中显示它时,我正在尝试与Jongo合作,并且非常希望在Java的Play 2.3.x中使用ObjectdWith morphia将用户名替换为“@Id ObjectId Id”。
controllers.Application.index(id: ObjectId)