这很好用:
@Repository
public interface VoteDao extends CrudRepository <Vote, Long> {
@Query(value = "select sum(points) from votes where siteuserid= ?1", nativeQuery = true)
int countBySiteUser(@Param("user") SiteUser user);
}
除非还没有投票,结果为 NULL,问题是我不知道如何处理检查它何时为 Null 的情况,因为当我询问时查询不返回任何内容......
System.out.println("!!!!: PROPOSAL VoteService: " + voteDao.countBySiteUser(user));
它应该为那个系统输出打印一个 Null 值吗? DAO 应该用 NULL 值来回答,但事实并非如此。如果提供,我将能够处理该 NULL,但事实并非如此。
预先感谢您的帮助!
最佳答案
使用COALESCE
将null
处理为0
,这与您实际的意思相对应。
@Query(
value = "SELECT COALESCE(SUM(points), 0) FROM votes WHERE siteuserid = ?1",
nativeQuery = true)
int countBySiteUser(@Param("user") SiteUser user);
...或其他采用编程方法的解决方案:
// Integer instead of int to add the "null" handling
@Query(
value = "SELECT SUM(points) FROM votes WHERE siteuserid = ?1",
nativeQuery = true)
Integer countBySiteUser(@Param("user") SiteUser user);
用法:
Integer count = voteDao.countBySiteUser(user);
if (count == null) {
count = 0;
}
System.out.println("!!!!: PROPOSAL VoteService: " + count);
COALESCE
解决方案对我来说似乎更好。但是作为@EJP说,这将取决于您的需求。
关于java - 在 spring jpa 中处理来自数据库的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43819683/