4

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

2 回答 2

1

我没有留下任何投票,但你应该提供更多的周边代码。在您提供的代码中大部分看起来都很好,但是如果您在事务中创建了书/章(未显示),则该章可能将书指定为父级,而您在手动时没有指定父级创建章节键。

于 2013-04-06T15:00:14.973 回答
0

您必须始终包含父实体键才能检索子实体。以下是如何创建包含父项的密钥:

Key keyBook = KeyFactory.createKey(Book.class.getSimpleName(),
    BOOK_ID); 

Key keyChapter = KeyFactory.createKey(keyBook,
    Chapter.class.getSimpleName(), CHAPTER_ID); 

Chapter chp = mgr.find(Chapter.class, keyChapter);

希望这可以帮助。

于 2013-04-08T18:53:51.973 回答