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

后端 未结 2 843
刺人心
刺人心 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.

提交回复
热议问题