0

I always get an null pointer exception because the results list is null and not empty. I thought that "problem" has been solved?

    Query query = em.createNamedQuery("findMaxTranslationId");
    query.setMaxResults(1);
    List<Long> results = query.getResultList();
    System.out.print(results); //Output = [null]
    Long translationId = 1L;
    if (!results.isEmpty()) {
        translationId = results.get(0); //null pointer exception
    }
    return translationId;

Query:

    SELECT MAX(t.translationId) FROM Translation t

I also tested the query manually and it is working.

perotom
  • 851
  • 13
  • 33
  • The output indicates that the list is not null. It contains a single element, which is null. And the NPE is probably not happening where you say it's happening. If the list was null, you would get it at the line with the `if` statement. Post the full stack trace to confirm. – JB Nizet Apr 06 '14 at 10:31
  • ok so how can i check if the list is "nearly" empty? – perotom Apr 06 '14 at 11:04
  • `if (results.get(0) != null) translationId = results.get(0);` – JB Nizet Apr 06 '14 at 11:10
  • thanks! But why does the query return null? – perotom Apr 06 '14 at 11:13
  • Because there is no translation at all in your table. – JB Nizet Apr 06 '14 at 11:17
  • thats right but why does to return a list with one object which is null and not an empty list? – perotom Apr 06 '14 at 11:23
  • Because the query returns a single value, whose value is null, and that you asked for a list of results. The single value returned by the query is thus stored in a list and the list is returned. If the query returned 0 result (like `select t from Translation t where t.translationId < 0`, for example), then you would get an empty list. – JB Nizet Apr 06 '14 at 11:25
  • Ah ok thanks! So the JPQL Function MAX returns null if there are no rows right? – perotom Apr 06 '14 at 11:32
  • JPQL is translated to SQL, and the SQL max function returns null if there are no values to compare. Execute the correcponding SQL query in your SQL tool, and you'll see. – JB Nizet Apr 06 '14 at 11:35

1 Answers1

0

The SQL Function "max" returns null if there are no rows to compare! So there will be a list with one object which is null returned.

perotom
  • 851
  • 13
  • 33