Spring JPA查询findByNameAndType返回null

时间:2015-12-10 18:46:02

标签: java spring-boot spring-data-jpa

我有一个接口公共接口IAllAccountsRepo扩展了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(当db中没有记录时)停止。我不想通过例外,需要忽略并继续,如果我能做到这一点。无论如何我可以编码它来忽略null并继续吗?或者我是否需要标准查询或任何其他?

for (String id : accountIdList) { accountEntityTemp = iAllAccountsRepo.findByIdAndAccounttype(id, accounttype); System.out.println("bs" + accountEntityTemp.getId()); if (accountEntityTemp != null) { accountsEntityList.add(accountEntityTemp); } } 对于一个id和accounttype,accountEntityTemp = null,我收到以下错误。

2015-12-10 14:20:03.784 WARN 10524 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver:处理程序执行导致异常:null

感谢。

2 个答案:

答案 0 :(得分:3)

呃...首先请... ..

@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更改为Integer,因为我不知道它的类型..

加上男人,有些关心潜在的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);
        }

答案 1 :(得分:0)

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

AccountEntity findByIdAndAccountType(Integer id, String accountType);