我有一个接口(interface) public interface IAllAccountsRepo extends CrudRepository
和下面的方法
@Query(value = "SELECT * FROM account a where a.id in :id AND a.accountType = :accountType", nativeQuery=true)
public AccountEntity findByIdAndAccountType(@Param("id") String id, @Param("accountType") String accountType);
当我在帮助程序类中调用此方法时,我将在其中获得一个 ID 列表并循环遍历它们并将过滤器值传递给上述方法,但是当没有与查询匹配的记录时我遇到了问题数据库。
它只是通过说 null 停止(当数据库中没有记录时)。我不想通过异常(exception),如果我能做到的话,需要忽略并继续。无论如何我可以编写代码以忽略 null 并继续吗?还是我需要条件查询或任何其他?
for (String id : accountIdList) {
accountEntityTemp = iAllAccountsRepo.findByIdAndAccounttype(id, accounttype);
System.out.println("bs"+ accountEntityTemp.getId());
如果(accountEntityTemp != null){
accountsEntityList.add(accountEntityTemp);
}
对于一个 ID 和帐户类型,accountEntityTemp = null,我收到以下错误。
2015-12-10 14:20:03.784 WARN 10524 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver:处理程序执行导致异常:null
谢谢。
最佳答案
嗯...首先请..
@Query(value = "SELECT * FROM account a where a.id =:id AND a.accountType = :accountType", nativeQuery=true)
public AccountEntity findByIdAndAccountType(@Param("id") String id, @Param("accountType") String accountType);
话虽这么说... 只是..为什么?你正在扩展 crudrepository,所以你也可以写
AccountEntity findByIdAndAccountType(String id, String accountType)
如果您在 AccountEntity bean 上的属性被命名 ID 帐户类型 或将 id 更改为整数,因为我不知道它的类型..
另外,注意一些潜在的 NPE.. 你告诉我们可能没有找到任何账户......但你确实找到了
accountEntityTemp = iAllAccountsRepo.findByIdAndAccounttype(id, accounttype);
System.out.println("bs" + accountEntityTemp.getId()); /// Null pointer here potentially...
if (accountEntityTemp != null) {
accountsEntityList.add(accountEntityTemp);
}
最多改成
accountEntityTemp = iAllAccountsRepo.findByIdAndAccounttype(id, accounttype);
if (accountEntityTemp != null) {
System.out.println("bs" + accountEntityTemp.getId());
accountsEntityList.add(accountEntityTemp);
}
关于java - Spring JPA 查询 findByNameAndType 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34209433/