【问题标题】:What is the difference between findById() and existsById() in Spring Data 2.0?Spring Data 2.0 中的 findById() 和 existsById() 有什么区别?
【发布时间】:2018-06-14 09:08:08
【问题描述】:

Spring Data 2.0 JpaRepository:findById()existsById() 之间的区别

  • 我们在哪种情况下使用findById()existsById() 方法?

【问题讨论】:

标签: java spring spring-data


【解决方案1】:

根据documentation

existsById(ID id) - 返回 boolean

返回具有给定 id 的实体是否存在。

findById(ID id) - 返回可选(对象)

通过 id 检索实体。

就这么简单 - findById() 返回您正在搜索的对象,existsById() 返回 true/false,无论实体是否存在于存储库中。

【讨论】:

  • 您好,请问从性能角度看哪一个更好?
【解决方案2】:

使用简单实体(id,name)对 findBy 和 existsBy 进行性能测试

【讨论】:

  • 添加额外的 100,000 条记录真的是 findBy 时间的两倍吗?
  • 这是我对开发环境的观察。如果其他人尝试并分享结果,我将不胜感激。
【解决方案3】:

findById(...) 和 getOne(...) 比 existsById(...) 快得多,现在还不清楚为什么要发明 existsById(...)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-06-05
  • 2013-01-15
  • 2021-11-11
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2012-12-10
相关资源
最近更新 更多