1

I have a method on my Spring Data repository interface defined like this:

@Query("SELECT MAX(e.index) FROM entity e WHERE e.companyId = :companyId AND e.userId = :userId") public Integer getMaxIndex(@Param("companyId") Long companyId, @Param("userId") Long userId); 

The calling code looks like this:

int currIndex = 0; Integer maxIndex = userActivityQueueRepository.getMaxIndex(companyId, user.getId()); if (null != maxIndex) { currIndex = maxIndex.intValue() + 1; } //else no records exist yet, so currIndex is 0 //create new records starting at currIndex and incrementing it along the way 

The problem is that when no records exist yet, it is returning 0 and not null. So, my currIndex gets set to 1 instead of 0. Is there something I'm doing wrong in the JPQL? Is there something I can add to the JPQL so it behaves as I was expecting it would?

I'm using version 1.7.2 of Spring Data JPA with PostreSQL and EclipseLink. I turned on the logging of SQL and ran the query manually in the database, and it gives the results I expect. I just don't understand why it isn't returning null when there are no records.

5
  • Have you tried changing method to return int instead of Integer? Commented Aug 4, 2015 at 20:11
  • @JakubKubrynski It just returns 0. I purposely made it an Integer so I could distinguish between no records and the max being 0. I may be missing something, but I don't see how having it return an int would help me at all. Commented Aug 4, 2015 at 20:17
  • What is the type of entity.index? Commented Aug 4, 2015 at 22:06
  • doesn't answer your question but given your code comments, are you sure you don't want to be doing Paging? also any chance that MAX() doesn't return null? Commented Aug 5, 2015 at 0:32
  • @Guillermo The index field on my entity is of type int. As soon as I saw that, I tried changing it to Integer, and now it is working as I expected. Go ahead and post an answer for this, and I'll accept it. Thanks. Commented Aug 5, 2015 at 14:39

1 Answer 1

1

For MAX function (MIN too) the result type is the type of the field, so to return null instead of 0, entity.index should be like Integer, Long but no int, long

See this table of the official documentation.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.