Home > Mobile >  Spring JPA Repository: What is the best practice, use findAllById or iterate over IDs and call getRe
Spring JPA Repository: What is the best practice, use findAllById or iterate over IDs and call getRe

Time:11-30

So, I'm in a situation where I need to get the reference of some entities in the database to vinculate them with another entity that has a relationship with them, but I'm in doubt of what is the better approach to achieve this.

I read some people saying that the repository.getReferenceById() throws and exception if the entity didn't exists with the given ID and, if exists, will load it in lazy mode. Thats good, because I don't need to access any attribute of the entity.

And the repository.findAllById() will return a list with all the entities found. Correct me if I'm wrong, but I feel that this method returns a list where the entities are also loaded in lazy mode.

So, I want to know what is the best approach to fetch the entities reference to associate it with another.

Some example code bellow:

// 1º Approach, using findAllById

List<Integer> themesIds = service.getThemesIds();  // This line is just to illustrate the flux

List<Theme> themesReference = themeRepository.findAllById(themesIds);

anotherEntity.setThemes(themesReference);
// 2º Approach, iterate over IDs and call getReferenceById

List<Integer> themesIds = service.getThemesIds();  // This line is just to illustrate the flux

List<Theme> themesReference = themesIds.stream()
                                       .map(id-> themeRepository.getReferenceById(id))
                                       .collect(Collectors.toSet());

anotherEntity.setThemes(themesReference);

I think that the first approach will result in only one query to fetch the entities, and it may can be better, and the second will perform N queries to fetch the entities, which I feel to be worst.

Which one I should use?

If you know another way to do this, share it with me

  • Related