why findAllById(…) is slower than findById(…) in a loop (JPA, HIBERNATE, JAVA, SPRING)

huangapple go评论45阅读模式
英文:

why findAllById(...) is slower than findById(...) in a loop (JPA, HIBERNATE, JAVA, SPRING)

问题

以下是您要翻译的内容:

"让我们假设我需要从数据库中获取10个实体,使用listIds。如果我使用listIds.stream来通过id获取每个实体 -> repository.findById(id),它比使用findAllById(listIds)更快,为什么会发生这种情况?

val listIds = List.of(1,2,3,4,5,6,7,8,9,10);

// 例子更快:
val entityList = listIds
.stream()
.map(id -> repository.findById(id).orElseThrow())
.collect(Collectors.toList());

// 例子更慢
val entityList = repository.findAllById(listIds);

这两个例子不在同一个事务中执行,它们只是方法的不同实现。"

英文:

Let's say I need to get 10 entities from the database using the listIds.
If I get from DB each entity by id using listIds.stream -> repository.findById(id), it works faster than findAllById(listIds)
why is this happening?

val listIds = List.of(1,2,3,4,5,6,7,8,9,10);

// example faster:
val entityList = listIds
            .stream()
            .map(id -> repository.findById(id).orElseThrow())
            .collect(Collectors.toList());


// example slower
val entityList = repository.findAllById(listIds);

the two examples are not executed in the same transaction, they are just different implementations of the method

答案1

得分: 1

也许大部分时间都用于与存储数据库的服务器通信。在第一种情况下,允许10次通信,而在第二种情况下,虽然有很多查询,但通信只发生一次。

想象一下,如果我是服务器,我们相隔100米。每次你向我请求数据,你都需要跑到我这里。如果你要求我告诉你昨天每个小时的温度,你只需要来回跑一次。
但是,如果你每次都问我1:00的温度和2:00的温度...你需要来回跑24次!

英文:

Perhaps most of the time is spent communicating with the server where the database is located. In the first case, 10 times are allowed, and in the second case, although there are many queries, the communication is once.

Imagine if I were the server and we were separated by 100 meters. Every time you request data from me, you need to run to me. If you ask me to tell you the temperature of each hour yesterday, you only need to run back and forth once.
But if, every time you ask me what is the temperature at 1:00 and what is the temperature at 2:00.. you need to run back and forth 24 times!

huangapple
  • 本文由 发表于 2023年2月8日 17:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定