我试图将一种实体放在与其父实体相同的实体组中。我在这里看了一些帖子,但似乎没有人有同样的问题所以我必须做错事(但我无法看到它)。
我有Brands(父亲)和Stores(儿子),我的问题是在尝试将商店添加到品牌时,出于某种原因,我得到了一个奇怪的NullPointerException。
Caused by: java.lang.NullPointerException
at com.google.appengine.datanucleus.scostore.FKListStore$3.fetchFields(FKListStore.java:1093)
...
以下是涉及的类以及将商店添加到父亲的代码:
@PersistenceCapable
public class Brand {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
protected String key;
@Persistent
@Extension(vendorName="datanucleus", key="gae.pk-id", value="true")
protected Long keyId;
@Persistent(defaultFetchGroup = "false")
private List<Store> stores;
}
这就是商店:
@PersistenceCapable
public class Store {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
protected String key;
@Persistent
@Extension(vendorName="datanucleus", key="gae.pk-id", value="true")
private Long keyId;
@Persistent(mappedBy = "stores")
protected BrandEntity brand;
}
在某个时刻创建了品牌,现在我想将商店添加到同一个实体组。没什么奇怪的:
public static StoreEntity addStore(String brandKey, Store store) {
PersistenceManager mgr = getPersistenceManager();
try {
BrandEntity brand = mgr.getObjectById(BrandEntity.class, brandKey);
if (brand != null){
brand.getStores(); //feth to retrieve collection from datastore
//add relationship
newStore.setBrand(brand);
List<StoreEntity> aux = brand.getStores(); //list is lazily fetched here
if (aux == null)
aux = new ArrayList<Store>(); //maybe is the first one ()
/*-- Nullpointer next line --*/
aux.add(newStore);
/*--NullPointer last line --*/
brand.setStores(aux);
brand = mgr.makePersistent(brand);
return store;
}
} finally{
mgr.close();
}
return null;
}
我知道在appengine文档示例中,“mappedBy =”nameOf theField“位于父级(我的情况下为Brand),而不是将其放在子级(Store),但我希望Store保持不变实体组比品牌。
所以,如果有人有任何建议,我会真的贬低它。
答案 0 :(得分:0)
&#34; mappedBy&#34; 处于错误的一端,请参阅JDO规范和http://www.datanucleus.org/products/accessplatform_3_3/jdo/orm/one_to_many_list.html#fk_bi 并且应该在&#34; Store&#34;之间进行1-N双向关系。和&#34;品牌&#34;,所以不知道什么&#34; BrandEntity&#34;与此有关。
PS。问题出在Google的插件中(如com.google程序包命名所示),而不是DataNucleus。
答案 1 :(得分:0)
感谢@Danaucleus解决我的问题。我的错误只是我手动将BrandEntity设置为Store的父级。
store.addBrand(theBrand); //this should not be done
brand.getStores().add(store);
但执行此操作时会自动填充此父关系:
brand.getStores().add(store);
另外,由于我想要一个双向关系,我必须在关系的两边放置“mappedBy”注释,这在BrandEntity类(父级):
@Persistent (mappedBy="brand")
private List<StoreEntity> stores;
这在StoreEntity类(子)
@persistent (mappedBy="stores"
BrandEntity brand;
所以我明确地错过了一些愚蠢的东西但是我得到的NullPointerException确实不清楚且无益。