Вопрос

У меня есть курс сущности, внутри которого есть ключ к другой сущности (Документу).

@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);
 }

В некотором тестовом коде я создаю новый объект Course и назначаю новый объект Document, и объект document сохраняется, когда я устанавливаю свойство document для course.Когда я сохраняю курс, он будет сохраняться без ошибок, однако, как только он будет сохранен, свойство document будет равно null.

Есть какие-нибудь идеи?Вот моя функция сохранения для курса:

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(длинный идентификатор) {

PersistenceManager pm = PMF.get().getPersistenceManager();Документ d = новый документ();

попробуйте { d = pm.getObjectById(Document.class , идентификатор);} наконец { pm.close();}

возврат d;}

Это было полезно?

Решение

  • Как выглядит класс Document как?
  • как выглядит класс 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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top