0

I have an entity which is expected to either be null or for there to be a single result. Currently I'm handling this like so:

    Entity entity = null;
    try {
        entity = query.getSingleResult();
    } catch (NoResultException ignore) {
        return null;
    }
    return entity;

But is this the "best" way of doing this? I'm not a fan of ignoring exceptions but equally not a big fan of the only alternative I can think of:

    List<Entity> entities = null;
    entities = query.getResultList();
    if (entities.size() > 0) {
        return entities.get(0);
    }
    return null;
Matt Fellows
  • 6,512
  • 4
  • 35
  • 57
  • 1
    tried using `Optional` ? – Vihar Jan 24 '18 at 11:37
  • http://sysout.be/2011/03/09/why-you-should-never-use-getsingleresult-in-jpa/ – daniu Jan 24 '18 at 11:39
  • 1
    @daniu - That article is a bit narrow and assumptive. I have a complex query which will result in one or null results. I don't use a NamedQuery for other reasons (code reuse of the predicates), so this is actually a genuine dilemma. – Matt Fellows Jan 24 '18 at 11:43

1 Answers1

2

You can find a discussion about this topic here: JPA getSingleResult() or null

Looks like there are no better alternatives.

gus3001
  • 851
  • 9
  • 19