Google DataStore 不存储子对象
-
13-09-2019 - |
题
我有一个实体课程,其中有另一个实体(文档)的密钥。
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class Course{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent private Key document;
public Document getDocument() {
if (document != null)
return new DocumentServiceImpl().getDocumentById(document.getId());
return null;
}
public void setDocument(Document document) {
if (document != null)
this.document = new DocumentServiceImpl().saveAndGetKey(document);
}
在一些测试代码中,我创建了一个新的课程实体,并分配了一个新的文档实体,并且当我在课程上设置文档属性时,该文档实体将被保留。当我坚持课程时,它将毫无错误地坚持下去,但是一旦坚持下去,文档属性将为空。
有任何想法吗?这是我的课程保存功能:
public Boolean save(Course c){
Boolean isSaved = false;
PersistenceManager pm = PMF.get().getPersistenceManager();
try{
pm.makePersistent(c);
isSaved = true;
}
catch(Exception e){
e.printStackTrace();
isSaved = false;
}
finally{
pm.close();
}
return isSaved;
}
编辑添加:
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class Document{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent private String data;
@Persistent private Set<Key> dTags;
@Persistent private Date dateCreated;
@Persistent private Date dateEdited;
public Document(){
this.dateCreated = new Date();
}
public Long getId() {
if (key == null){
return null;
} else {
return key.getId();
}
}
public void setId(Long id) {
if (id != null)
key = KeyFactory.createKey(this.getClass().getSimpleName(), id);
}
来自 DocumentServicesImpl:
public Key saveAndGetKey(Document d) {
try{
if (d.getKey() == null){
save(d);
}
return d.getKey();
} catch (Exception e){
return null;
}
}
public Boolean save(Document d) {
Boolean isSaved = false;
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(d);
isSaved = true;
} catch (Exception e) {
e.printStackTrace();
isSaved = false;
}finally{pm.close();}
return isSaved;
}
公共文档 getDocumentById(长 id) {
PersistenceManager pm = PMF.get().getPersistenceManager();文档 d = new Document();
尝试{d = pm.getObjectByid(document.class,id);}最后{pm.close();}
返回d;}
解决方案
- 文档类是什么样的?
- DocumentServiceImpl 类是什么样的?
- 您的单元测试 saveAndGetKey() 看起来像什么?它是否检查返回值是否是有效的密钥?然后您可以在数据存储中查找该文档吗?
- 您的ServiceImpl类是可以持久的,还是持久的?我不确定它们是否需要仅基于您向我们展示的内容。
新的故障排除思路如下:如果你尝试这样简单的事情会发生什么:现在,将 Course.document 公开。然后看看这种更简单的创建实体的方法是否有效。
pm = yourPMfactory.getPersistenceManger();
Course c = new Course();
Document d = new Document();
c.document = d;
pm.makePersistent(c);
Key myKey = c.getKey();
Course c2 = (Course) pm.getObjectById(Course.class, myKey.getId());
assertTrue(c.document != null); //or however your favorite test suite does assertions.
pm.close();
不隶属于 StackOverflow