【发布时间】:2015-08-04 20:08:47
【问题描述】:
我的 Spring Data 存储库接口上有一个方法,定义如下:
@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 以使其行为符合我预期的内容吗?
我正在使用带有 PostreSQL 和 EclipseLink 的 Spring Data JPA 1.7.2 版。我打开了 SQL 的日志记录并在数据库中手动运行查询,它给出了我期望的结果。我只是不明白为什么没有记录时它不返回null。
【问题讨论】:
-
您是否尝试过将方法更改为返回 int 而不是 Integer?
-
@JakubKubrynski 它只返回 0。我故意将其设为整数,以便区分无记录和最大值为 0。我可能遗漏了一些东西,但我不知道它是如何返回的一个 int 对我有帮助。
-
entity.index的类型是什么? -
没有回答您的问题,但鉴于您的代码 cmets,您确定不想进行分页吗?还有 MAX() 不返回 null 的机会吗?
-
@Guillermo 我实体上的索引字段的类型为
int。我一看到就尝试将其更改为Integer,现在它可以按预期工作了。继续并为此发布答案,我会接受它。谢谢。
标签: spring-data-jpa jpql