Nullpointerexception throws when inserting entity using Auto-generated Classendpoint insert method

不羁岁月 提交于 2019-12-01 04:19:30

I had exactly the same problem. I will present the way I worked around it.

Original auto-generated Endpoints class relevant code:

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;
}

Changed relevant code to include a null check for the entity object that is passed as an argument.

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;
}

This way it will work as supposed, although I'm confident that more experienced answers and explanations will appear.

I was having the same exact problem after using the Eclipse Plugin to autogenerate the cloud endpoints (by selecting "Google > Generate Cloud Endpoint Class").

Following your advice, I added:

if(foo.getID() == null) // replace foo with the name of your own object return false;

The problem was solved.

How is that Google hasn't updated the autogenerated code yet as this must be a highly recurring issue?

Thanks for the solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!