我正在使用 gwt 和 jdo datanucleus。我有要求让 child 和 parent 在一起。但当访问父级时我没有得到子级。 我的代码如下
我的父类是
@PersistenceCapable(identityType = IdentityType.APPLICATION, table = "user")
public class User implements Serializable {
private static final long serialVersionUID = 2660867968471555842L;
@PrimaryKey
@Persistent
private String email;
@Persistent(defaultFetchGroup = "true",mappedBy="user")
private UserProfile profile;
public User() {}
public User(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public UserProfile getProfile() {
return profile;
}
public void setProfile(UserProfile profile) {
this.profile = profile;
}
}
我的 child 类(class)是
@PersistenceCapable(identityType = IdentityType.APPLICATION,table = "user_profile")
public class UserProfile implements Serializable {
private static final long serialVersionUID = -6818036410894395030L;
@PrimaryKey
@Persistent(defaultFetchGroup="true")
private User user;
@Persistent
private String name;
public UserProfile() {}
public UserProfile(User user) {
this.user = user;
user.setProfile(this);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我正在通过以下查询获取数据
PersistenceManager pm = PMF.get().getPersistenceManager();
User user=null;
try{
String userId ="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61000302210003024f020e0c" rel="noreferrer noopener nofollow">[email protected]</a>";
Query userQuery = pm.newQuery(User.class);
userQuery.setFilter("email == '" + userId + "'");
userQuery.setUnique(true);
user = (User) userQuery.execute();
} catch (Exception e) {
throw new IllegalAccessError("Failed to get the User..");
}finally{
pm.close();
}
但我在对象用户中得到的用户配置文件为空。 哪里有问题 ? 如何为子级加载父级?
最佳答案
我不确定您是否找到了答案,但对于那些偶然发现这个问题的人,我只是想分享我是如何让它发挥作用的。
@PersistenceCapable(detachable = "true")
@FetchGroup(name = "fooGroup", members = { @Persistent(name = "list") })
public class ParentClass {
@Persistent(mappedBy = "parent")
@Element(dependent = "true") //can not exist without parent
private List<ChildClass> list;
}
@PersistenceCapable(detachable = "true")
public class ChildClass {
@Persistent
private ParentClass parent;
}
然后进行抓取:
PersistenceManager pm = PMF.get("eventual-reads-shortdeadlines").getPersistenceManager();
pm.setDetachAllOnCommit(true);
pm.getFetchPlan().addGroup("fooGroup");
Transaction tx = pm.currentTransaction();
try {
tx.begin();
Query query = pm.newQuery(ParentClass.class);
list = (List<ParentClass>) query.execute();
tx.commit();
} catch (Exception ex) {
...
} finally {
if (pm != null) {
if(pm.currentTransaction().isActive()){
pm.currentTransaction().rollback();
}
pm.close();
}
}
您的 ParentClass 现在应该拥有每个的所有 ChildClass。希望有帮助!
关于google-app-engine - jdo 中的子级不与父级一起获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10550230/