我有两个模型,书籍和章节,是一对多的关系。我为 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);