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:
Asked
Active
Viewed 264 times
2
-
`.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 Answers
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
-
it seems query.getResultList() return size of 1 even there is no result in the query. – Apr 23 '21 at 10:13
-
-
its kinda weird since, its not looping. but the arraysize is = 1. maybe because of the SELECT MAX aggregate? – Apr 23 '21 at 11:03
-
-
I tried to remove. but its the same.. thats why its weird. I think the MAX is really returning null. – Apr 23 '21 at 11:48
-
-
confirmed. List
objs will have an element that is null. if SELECT MAX returns null. for example the table is empty. – Apr 23 '21 at 12:41 -
[Yes, that's true indeed @daniel.chan](https://stackoverflow.com/questions/1688715/select-maxx-is-returning-null-how-can-i-make-it-return-0) – Yassin Hajaj Apr 23 '21 at 12:44