Book と Chapter の 2 つのモデルが 1 対多の関係にあります。Book と Chapter の両方のキーを手動で作成します。永続化するには、book オブジェクトを作成し、それに章のインスタンスを追加してから、book を永続化します。データストアに表示されるので、これは正常に機能します。キーでデータストアから章を取得しようとすると、null オブジェクトが返されます。
キーがデータストアでどのように見えるかを次に示します。
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でも同じことを試してみましたが、うまくいきました。したがって、問題はチャプターにあります。おそらく、Chapter から 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);