Spring JPA 查询 findByNameAndType returns 空

Spring JPA query findByNameAndType returns null

我有一个接口 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);

当我在助手 class 中调用此方法时,我将在其中获得一个 ID 列表并循环遍历它们并将过滤器值传递给上述方法,但是当有数据库中没有匹配查询的记录。

它只是说null(当数据库中没有记录时)就停止了。我不想通过例外,如果我能做到的话,需要忽略并继续。无论如何我可以编写代码以忽略 null 并继续吗?还是我需要条件查询或任何其他?

for (String id : accountIdList) { accountEntityTemp = iAllAccountsRepo.findByIdAndAccounttype(id, accounttype); System.out.println("bs" + accountEntityTemp.getId()); if (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

谢谢。

我什至不知道为什么在为 id 传递单个参数时使用 IN 函数。 不过,您想要的方法应该如下所示:

AccountEntity findByIdAndAccountType(Integer id, String accountType);

嗯...首先请..

@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);
        }