自動生成されたエンドポイント クラスの使用について混乱しています。生成されたエンドポイントを使用して、新しいオブジェクトをデータストアに挿入したいと考えています。ただし、スローは例外です。
fooEndpoint.insertFoo(foo); // throws null pointer exception
私のエンティティ クラスは、https://developers.google.com/appengine/docs/java/datastore/jpa/overview のソースにある例と似てい ます。
ここに私のエンティティがあります:
@Entity
public class Foo {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Key ID;
スタック トレースは次のとおりです。
java.lang.NullPointerException
at org.datanucleus.api.jpa.JPAEntityManager.find(JPAEntityManager.java:318)
at org.datanucleus.api.jpa.JPAEntityManager.find(JPAEntityManager.java:256)
at com.FooEndpoint.containsFoo(FooEndpoint.java:150)
at com.FooEndpoint.insertFoo(FooEndpoint.java:96)
一方、EntityManager の persist メソッドを使用すると、新しいオブジェクトを挿入できます。これは、データストアに存在するかどうかをチェックしないためです。
classEndpoint 挿入メソッドはオブジェクトを保存し、自動キーを ID フィールドに割り当てる必要があると思います。
または、ID フィールドを初期化する必要があります。
これは、自動生成されたエンドポイント クラスの insertFoo メソッドです。
/**
* This inserts a new entity into App Engine datastore. If the entity already
* exists in the datastore, an exception is thrown.
* It uses HTTP POST method.
*
* @param foo the entity to be inserted.
* @return The inserted entity.
*/
public Foo insertFoo(Foo foo) {
EntityManager mgr = getEntityManager();
try {
if (containsFoo(foo)) {
throw new EntityExistsException("Object already exists");
}
mgr.persist(foo);
} finally {
mgr.close();
}
return foo;
}
これがcontainsFooメソッドです
private boolean containsFoo(Foo foo) {
EntityManager mgr = getEntityManager();
boolean contains = true;
try {
Foo item = mgr.find(Foo.class, foo.getID()); // exception occurs here
if (item == null) {
contains = false;
}
} finally {
mgr.close();
}
return contains;
}
foo.getID() が null です。なぜなら、それは新しいオブジェクトです。アプリエンジンがキーを作成することを期待しています。または、明示的にキーを作成する必要がありますか?
Foo クラスの他のフィールドは、String や booleans などの単純な型です。
御時間ありがとうございます。