【问题标题】:Spring data JPA null record check?Spring数据JPA空记录检查?
【发布时间】:2022-01-04 08:02:31
【问题描述】:

我有一个存储库类,我在其中扩展了 JPARepository 并创建了一个从表中获取记录列表的查询。

ICA ica = null;
ica = brRepository.findByNameAndId(name , id);

现在当这个ica = brRepository.findByNameAndId(name , id);被执行并且假设表中没有记录ica的值是什么

只会为空吗?

基本上,我想将ica 与 null 进行比较,如果它为 null,则记录其他内容。 是比较正确的方法还是安全操作?

if(ica == null){
System.out.println("Null");
}
else{
System.out.println("there is one record");
}

【问题讨论】:

  • "只会为 null 吗?" - 我不完全确定您的意思,但为什么不试试呢?

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


【解决方案1】:

根据 Spring-Data-JPA 的新版本,支持并鼓励使用 Optionals。

Optional<ICA> ica = brRepository.findByNameAndId(name , id);


if(ica.isPresent()){
  System.out.println("there is one record");
} else{
  System.out.println("Null");
}

您还必须修改存储库中定义的方法以返回Optional&lt;ICA&gt; findByNameAndId

【讨论】:

  • 我认为条件应该是相反的if(ica.isPresent()){System.out.println("there is one record"); } else{ System.out.println("null"); }
  • @Learners 正确我更新了 :)
猜你喜欢
  • 2020-03-13
  • 2017-01-13
  • 2019-05-30
  • 2021-04-23
  • 2020-04-01
  • 2013-12-24
  • 2020-01-05
  • 2014-08-08
  • 2018-06-13
相关资源
最近更新 更多