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

后端 未结 2 844
刺人心
刺人心 2021-01-12 10:01

I am confused to using auto-generated endpoint class. I want to use generated endpoint to insert new object into datastore. But, an exception is throwing.

f         


        
相关标签:
2条回答
  • 2021-01-12 10:46

    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.

    0 讨论(0)
  • 2021-01-12 10:47

    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.

    0 讨论(0)
提交回复
热议问题