我有一个实体课程,里面有另一个实体(文档)的密钥。
@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(Long id) {
PersistenceManager pm = PMF.get().getPersistenceManager(); 文档 d = new Document();
尝试 { d = pm.getObjectById(Document.class, id); } 最后 { pm.close(); }
返回 d; }