javahibernatespring-mvcnullpointerexception

How I can compare Null entity without throws NullPointerException


I have a method who gets some data with Hibernate, but if the entity is Null, when I try to compare with it throws NullPointerException

ExampleController.java

@RequestMapping(value = "/example/{exampleId}")
    public String exampleMethod(@PathVariable("exampleId") final Integer exampleId, final ModelMap model) {

        ExampleEntity ee = this.ExampleEntityService.load(exampleId);
        if (ee.exampleAnidatedEntity() == null) {
            model.addAttribute("exampleAnidatedEntity", ee.exampleAnidatedEntity());
        } else {
            model.addAttribute("exampleAnidatedEntity", new ExampleAnidatedEntity());
        }

// Do some stuff...

Solution

  • Change this to

    if (ee!=null && ee.exampleAnidatedEntity() == null) {
    

    This will make the checking only when ee is not null.