【发布时间】:2016-01-27 23:42:40
【问题描述】:
我正在使用 jersey-quickstart-webapp(Glassfish,v2.22.1)为我的 MongoDB 数据库构建 REST API。
应用服务器是 Tomcat 8(在 IntelliJ Idea 中运行)和 Morphia (v1.1.0)。
一个。我的Org类如下...
@Entity(value = "orgs", noClassnameStored = true)
public class Org
{
@Id
@Property("id")
private ObjectId id;
private String name = null;
// Some other properties
// Getter/Setter for Object ID
public ObjectId getId(){return id;}
public void setId(ObjectId id){this.id = id;}
// Getter & Setter for name...
// the other Getter & Setter methods
}
b.我的 OrgResource(POST 方法)如下...
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Org createOrg(Org org)
{
Morphia morphia = new Morphia();
morphia.mapPackage("com.dgfx.entity");
try
{
Datastore ds = morphia.createDatastore(MongoDBHelper.getMongoClient(), "dgfx-admin");
ds.save(org);
System.out.println("org name = " + org.getName() + ", id = " + org.getId()); // Prints the new Org ID perfectly fine!!!
return org;
} catch (UnknownHostException e)
{
e.printStackTrace();
return null; //TODO: Better return type
}
}
c。 POST 请求(使用 Postman 和 ContentType:Application/JSON)...
{
"altName": "",
"levels": [],
"name": "My Organisation",
"parentId": "",
"shortName": "",
"type": ""
}
d。执行 POST 后,MongoDB Collection 中的数据看起来不错...
> db.orgs.find();
{ "_id" : ObjectId("56a9462902c3192d88d64bc3"), "type" : "", "name" : "My Organisation", "altName" : "", "shortName" : "", "parentId" : "" }
{ "_id" : ObjectId("56a9464b02c3192d8845d128"), "type" : "", "name" : "Ecosys Clover", "altName" : "", "shortName" : "", "parentId" : "" }
e。直到这里,一切都像一个魅力,SysOut 打印出 Org 新创建的 id...
ds.save(org);
System.out.println("org name = " + org.getName() + ", id = " + org.getId()); // Prints the new Org ID perfectly fine!!!
f。但是,当作为 POST 调用的响应返回相同的 Org 时,它不包含新 ID!!!
{
"altName": "",
"id": {},
"levels": [],
"name": "My Organisation",
"parentId": "",
"shortName": "",
"type": ""
}
如果我在这里做错了什么,请告诉我?由于 Org ID 是从 Org Object 打印的,因此在 DB 中的插入,Org object Id 上的更新(通过 Morphia)似乎工作正常。可能问题出在返回类型的某个地方,或者我在某个地方犯了一些非常根本的错误......
g.调查完毕
- 尝试将私有 ObjectId id 更改为 _id:没有运气
- 尝试将私有 @Property("id") 更改为 "_id":没有运气
- 尝试对已使用 GET 创建的对象进行简单查询:行为相同
- 在 OrgResource.POST 中更新 Org 的另一个字段,这确实会反映在 POST 响应中!
提前感谢任何帮助和感谢...
SG
【问题讨论】:
标签: json mongodb rest jersey-2.0 morphia