Proper way to to handle null in getSingleResult aggregate

Viewed 129

is there any proper way to handle null for example there is no existing record in the Users table, so it wont throw null pointer:

1 Answers

If the record does not exist in the database, do not use getSingleResult(). Looking at the javadoc, you need to be sure the record exists to use getSingleResult()

getSingleResult

java.lang.Object getSingleResult()

Execute a SELECT query that returns a single untyped result.

Returns: the result

Throws:

NoResultException - if there is no result

NonUniqueResultException - if more than one result

Instead, use getResultList()

public long generateNextId() {
    Query query = getEntityManager().createQuery("SELECT MAX(id)+1 from Users");
    List<Object> objs = query.getResultList();
    return objs.isEmpty() ? 1 : Long.parseLong(objs.get(0));
}

Also, further, I'd use a TypedQuery<Long> if I were you

public long generateNextId() {
    TypedQuery<Long> query = getEntityManager().createQuery("SELECT MAX(id)+1 from Users", Long.class);
    List<Long> objs = query.getResultList();
    return objs.isEmpty() ? 1 : objs.get(0);
}

If, like documented in this question, the query can return null then you can just use a null check or use an Optional#ofNullable wrapper

Related