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.
entity.index?int. As soon as I saw that, I tried changing it toInteger, and now it is working as I expected. Go ahead and post an answer for this, and I'll accept it. Thanks.