毕竟,您可能正在寻找Morphia、 MongoDB ORM for Java 吗?对于Morphia来说,Slideshare 中的本教程可能是一个很好的起点。
顺便说一句,我发现_id
用户名 String 比 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" } }
>