Appengine JDO, how can I retrieve a child object knowing a child property and the parent key?
Using the peristance manager, how can I retrieve a child object knowing a child property and the parent key?
The Parent is defined like this:
public class User {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key id;
@Persistent(mappedBy = "user")
@Element(dependent = "true")
private List<Section> sections;
...
And the child is defined like this:
public class Section {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
private User user;
@Persistent
private String title;
...
Knowing the 'User' id and the 'Section' title, how can I retrieve the section?. I was trying to build a query to retrieve the section using something like this: 'where title == xxx AND user.id ¿? == xxx' but I'm not sure how to specify the user id. Is there any way to do it using queries or methods from the persistanc开发者_如何学运维e manager?
Thanks.
I finally made it with this method:
public static Section getSectionByTitle(String title, Key user_key){
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select from "+Section.class.getName()+" WHERE title == s && user == keyParam");
query.declareParameters("String s, String k");
query.setUnique(true);
Section section = (Section) query.execute(title, user_key.getId());
return section;
}
You can call this method on the query object:
q.setAncestor(ancestorKey);
Read this page for more information (Ancestor Queries).
I remember seeing something like 'where ANCESTOR = ' syntax but I cannot find any reference for it now.
精彩评论