Spring 数据 JPA 查询返回对象,即使结果为空
Spring Data JPA query returning Object even though result is null
我的 Spring 数据存储库接口上有一个方法定义如下:
@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);
调用代码如下所示:
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
问题是当不存在任何记录时,它返回 0
而不是 null
。因此,我的 currIndex 设置为 1
而不是 0
。我在 JPQL 中做错了什么吗?有没有我可以添加到 JPQL 中的东西,以便它的行为符合我的预期?
我将 Spring Data JPA 1.7.2 版与 PostreSQL 和 EclipseLink 一起使用。我在数据库中手动打开了 SQL 和 运行 查询的日志记录,它给出了我期望的结果。我只是不明白为什么没有记录时它不返回 null
。
对于 MAX 函数(MIN 也是),结果类型是字段的类型,因此 return null 而不是 0,entity.index
应该像 Integer
、Long
但没有 int
、long
参见官方文档this table。
我的 Spring 数据存储库接口上有一个方法定义如下:
@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);
调用代码如下所示:
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
问题是当不存在任何记录时,它返回 0
而不是 null
。因此,我的 currIndex 设置为 1
而不是 0
。我在 JPQL 中做错了什么吗?有没有我可以添加到 JPQL 中的东西,以便它的行为符合我的预期?
我将 Spring Data JPA 1.7.2 版与 PostreSQL 和 EclipseLink 一起使用。我在数据库中手动打开了 SQL 和 运行 查询的日志记录,它给出了我期望的结果。我只是不明白为什么没有记录时它不返回 null
。
对于 MAX 函数(MIN 也是),结果类型是字段的类型,因此 return null 而不是 0,entity.index
应该像 Integer
、Long
但没有 int
、long
参见官方文档this table。