javaspring-boothibernatenested-loopsjparepository

Hibernate: findById vs findAllById, what to use for list of ids and non-nested for loops


  1. I have a list of ids that are associated with objects to fetch. I need to process each object after fetching them.

    Should I get the list of objects using findAllById, so there will be one DB call and then process the result using for loop?

    OR

    Should I run the for loop for ids, and process each object using findById? Which seems bad as it will do multiple DB calls.

  2. Is multiple non-nested for loop better than multiple DB calls?


Solution

    1. Its better using findAllByIds because one DB call and if you want to process each data, you can achieve that by doing loop/foreach/stream

    2. Yes, because it would decrease the minimum of error by creating DB call.