Mik*_*ike 3 java spring hibernate jpa
这很好用:
@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);
}
Run Code Online (Sandbox Code Playgroud)
除非在没有投票的情况下结果为NULL并且问题是我不知道如何处理检查何时为Null,因为当我问...时查询没有返回任何内容...
System.out.println("!!!!: PROPOSAL VoteService: " + voteDao.countBySiteUser(user));
Run Code Online (Sandbox Code Playgroud)
它应该为该sysout打印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);
Run Code Online (Sandbox Code Playgroud)
......或采用程序化方法的其他解决方案:
// 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);
Run Code Online (Sandbox Code Playgroud)
用法:
Integer count = voteDao.countBySiteUser(user);
if (count == null) {
count = 0;
}
System.out.println("!!!!: PROPOSAL VoteService: " + count);
Run Code Online (Sandbox Code Playgroud)
该COALESCE解决方案似乎不如我.但正如@EJP所说,这将取决于您的需求.