我正在使用gwt和jdo datanucleus。我要求与父母一起生孩子。但是我在访问父母时没有得到孩子。 我的代码如下
我的父类是
@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;
}
}
我的孩子班是
@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 ="abc@abc.com";
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();
}
但我在对象用户中获取userprofile null。 问题出在哪儿 ? 如何用父母加载孩子?
答案 0 :(得分:2)
我不确定你是否找到了自己的答案,但对于那些偶然发现这一点的人我只是想分享一下我是如何运作的。
@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。希望有所帮助!