gpt4 book ai didi

google-app-engine - 使用自动生成的类端点插入方法插入实体时抛出 Nullpointerexception

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:30 25 4
gpt4 key购买 nike

我对使用自动生成的端点类感到困惑。我想使用生成的端点将新对象插入数据存储区。但是,抛出异常。

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() 为空。因为,它是新对象。我期待 App Engine 为它创建一个 key 。或者我需要明确地为它创建一个 key ?

Foo 类中的其他字段是简单类型,例如 String 和 booleans。

感谢您的宝贵时间。

最佳答案

我遇到了完全相同的问题。我将介绍我的工作方式。

原始自动生成的端点类相关代码:

private boolean containsFoo(Foo foo) {
EntityManager mgr = getEntityManager();
boolean contains = true;
try {
Foo item = mgr.find(Foo.class, foo.getID());
if (item == null) {
contains = false;
}
} finally {
mgr.close();
}
return contains;
}

更改了相关代码以包括对作为参数传递的实体对象的空检查。

private boolean containsFoo(Foo foo) {
EntityManager mgr = getEntityManager();
boolean contains = true;
try {
// If no ID was set, the entity doesn't exist yet.
if(foo.getID() == null)
return false;
Foo item = mgr.find(Foo.class, foo.getID());
if (item == null) {
contains = false;
}
} finally {
mgr.close();
}
return contains;
}

这样它会按预期工作,尽管我相信会出现更有经验的答案和解释。

关于google-app-engine - 使用自动生成的类端点插入方法插入实体时抛出 Nullpointerexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15226793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com