How to auto-fetch JDO nested collection of entitie

2019-02-14 22:19发布

Probably a very trivial problem.

I have an object that looks like this:

@PersistenceCapable  
public class Parent {

  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  private String _id;

  @Persistent
  private List<Child> _children;

   //...   
}

... the nested entity looks like this (I am forced to declare primary key as Key otherwise it won't persist):

@PersistenceCapable  
public class Child {

   @PrimaryKey
   @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
   private Key _id; 

   @Persistent
   private String _whatever;

   //... 
}

When I persist everything gets persisted OK (including Child entities), but I would like to get back everything by getting the parent object (e.g. getObjectById), but the collection comes back as null.

Owned One-to-Many Relationships seem to be what I am looking for -- but I am having trouble to see how it can help me to get back the parent object with the populated collection of children entities.

Any help appreciated!

2条回答
▲ chillily
2楼-- · 2019-02-14 22:59

this seems to do the trick:

@Persistent(defaultFetchGroup = "true")
查看更多
迷人小祖宗
3楼-- · 2019-02-14 23:07

@Persistent(defaultFetchGroup = "true") Does the trick, you're right.

The content of your _children attribute is loaded only when you access it (before pm.close !) for the first time. It's called lazy-loading. If you want to have the child Entity or Collection of Child Entities to be directly loaded by default, apply the above "trick".

In my app, in case of a Collection of child Entities, it generates an Error message (Datastore does not support joins..) on the Dev Server, but you can ignore this wrong error, it is working fine in Dev and Prod Environments.

Be aware that fetching a Collection through it's parent Entity costs 1 datastore fetch per Child Entity.

查看更多
登录 后发表回答