2

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:

  • `.getSingleResult()` should be only used for queries when **single** result is guaranteed. Not multiple result, not empty result, but **single**. Perfect example - count queries (`select count(...)`), they never return null or multiple result – Nikolai Shevchenko Apr 23 '21 at 11:38
  • But the (Select MAX) is returning null. –  Apr 23 '21 at 12:04

1 Answers1

2

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

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89