0
我正在爲使用MongoDb和Morphia的應用程序編寫後端,但我遇到了保存嵌入對象的一個有趣問題。Morphia Query在第二次搜索時返回Null,而不是第一次?
假設我在寫論壇軟件。有帖子(父對象)和評論(子對象)。每個帖子包含一個評論的ArrayList。我可以發佈帖子,然後添加一條評論。這工作正常。如果我嘗試添加第二條評論,看起來好像我的Morphia查詢在搜索帖子以附加評論時返回空對象。
下面是代碼,這是我processComment方法中:
// Get Owner and ParentObjectId from the incoming JSONObject.
String commentOwner = jsonObject.getString("owner");
String parentObjectUuid = jsonObject.getString("parentObjectUuid");
// Create a new Comment from these values, and add the body.
Comment comment = new Comment(commentOwner, parentObjectUuid);
comment.setBody(jsonObject.getString("body"));
// Get Parent Object from Datastore.
Query<Post> query = datastore.createQuery(Post.class);
query.field("uuid").equalIgnoreCase(parentObjectUuid);
Post parentObject = query.get(); // <--- This is Line #144 where I think it fails.
// Add comment to its ParentObject, and save in our datastore.
parentObject.addComment(comment);
datastore.save(parentObject);
Here is the stacktrace:
java.lang.RuntimeException: java.lang.NullPointerException
at org.mongodb.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:76)
at org.mongodb.morphia.mapping.Mapper.readMappedField(Mapper.java:850)
at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:282)
at org.mongodb.morphia.mapping.Mapper.fromDBObject(Mapper.java:193)
at org.mongodb.morphia.query.MorphiaIterator.convertItem(MorphiaIterator.java:134)
at org.mongodb.morphia.query.MorphiaIterator.processItem(MorphiaIterator.java:146)
at org.mongodb.morphia.query.MorphiaIterator.next(MorphiaIterator.java:117)
at org.mongodb.morphia.query.QueryImpl.get(QueryImpl.java:236)
at org.mongodb.morphia.query.QueryImpl.get(QueryImpl.java:227)
at IncomingProcessor.processComment(IncomingProcessor.java:144)
at IncomingProcessor.processIncomingJson(IncomingProcessor.java:78)
at IncomingProcessor.<init>(IncomingProcessor.java:50)
at Main.main(Main.java:78)
Caused by: java.lang.NullPointerException
at org.mongodb.morphia.Key.hashCode(Key.java:149)
at java.util.HashMap.hash(HashMap.java:338)
at java.util.HashMap.put(HashMap.java:611)
at org.mongodb.morphia.mapping.cache.DefaultEntityCache.notifyExists(DefaultEntityCache.java:82)
at org.mongodb.morphia.mapping.cache.DefaultEntityCache.putEntity(DefaultEntityCache.java:90)
at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:293)
at org.mongodb.morphia.mapping.EmbeddedMapper.readMapOrCollectionOrEntity(EmbeddedMapper.java:210)
at org.mongodb.morphia.mapping.EmbeddedMapper.readCollection(EmbeddedMapper.java:144)
at org.mongodb.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:47)
... 12 more
只是要清楚,這個代碼工作的第一次。當我嘗試添加第二個評論時,它失敗。 任何想法?謝謝。
IncomingProcessor.processIncomingJson(IncomingProcessor.java:78)'不是NPE嗎? 'jsonObject.getString(「owner」)'對我來說看起來很奇怪 - Morphia應該自動處理它。您不需要手動映射成員變量。 – xeraa