0

I'm working on a JavaEE application with EJB and JPA.

When I try to get an entity that doesn't exist in the EntityManager an exception occurs. but when I do:

Entity e=em.find(Entity.class,primarykey);
if(e.equals(null)){
      return "error!";
}

Can please someone help me solve this problem?

Ghost
  • 113
  • 4
  • 11
  • Object equals `null` is never true. Therefore, you should do `if(e == null){...}` instead. – Tiny Dec 31 '14 at 22:51

1 Answers1

1

As suggested in the comment you have to use the == operator to check for null, because if the object you want to check is null, you can't use the equals() method (or any other method) on this null type instance.

Solution example:

public boolean isEntityNull(Class clazz, Object primaryKey) {
    Entity e = em.find(clazz, primaryKey);
    if (e == null) {
        return true;
    } else {
        return false;
    }
}

See also:

Community
  • 1
  • 1
unwichtich
  • 13,712
  • 4
  • 53
  • 66