我有两种模式,书和章,采用一对多的关系。我手动创建Book和Chapter的键。坚持下来,我创建一个书对象,然后添加一个章节的实例,然后坚持书。这很好,因为我在数据存储中看到它们。现在,当我试图通过键从数据存储中获取一章时,我得到一个空对象。通过键查询数据存储库时无效
这里是关键如何看待在数据存储:
Under Book: name/id = 123 chapters = [Book(123)/Chapter("abc")]
Under Chapter: name/id = abc
我创造了我的钥匙,无论是用于创建和获取对象,使用
Key key = KeyFactory.createKey(Chapter.class.getSimpleName(), chapterId);
我取的代码是这样的:
Key key = KeyFactory.createKey(Chapter.class.getSimpleName(), chapterId);
Chapter chp = mgr.find(Chapter.class, key);//chp is always null (yes in debug mode as well)
更新:
我在书上尝试同样的事情,它工作正常。所以问题在于章节。也许这是因为我通过Book保存了章节(但我在上面提到的数据存储中都可以看到)。
所以问题是:有没有一种方法来独立检索章节(通过它的关键),如果是的话,一个代码段请。
更新源代码:
@Entity
public class Book implements java.io.Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Chapter> Chapters = new ArrayList<Chapter>();
public List<Chapter> getChapters() {
return Chapters;
}
public void setChapters(List<Chapter> Chapters) {
this.Chapters = Chapters;
}
public Book(long num, List<Chapter> Chapters) {
super();
Key key = KeyFactory.createKey(Book.class.getSimpleName(), num);
this.key = key;
this.Chapters = Chapters;
}
public Book(long num) {
super();
Key key = KeyFactory.createKey(Book.class.getSimpleName(), num);
this.key = key;
}
public Book() {
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
}
@Entity
public class Chapter implements java.io.Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String content;
public Chapter(String ChapterId, String content) {
super();
Key key = KeyFactory.createKey(Chapter.class.getSimpleName(), ChapterId);
this.key = key;
this.content = content;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public String getContent() {
return content;
}
public void set content(String content) {
this.content = content;
}
}
代码添加:
Book bk = new Book(num);
Chapter chp = new Chapter(ChapterId, content);
bk.getChapters().add(chp);
bookDao.put(bk);
mgr.persist(bk);
尝试'mgr.find(Chapter.class,chapterId)' – 2013-04-06 12:02:40
@PeterKnego这是我尝试的第一件事:也不管用。 – learner 2013-04-06 12:13:14
看来这个问题得到4票和1票反对票。对于那些倒票的人,如果你觉得这个问题微不足道,你能否提供答案? SO建议您发表评论。 – learner 2013-04-06 12:41:45