Rafael Furtado
Rafael Furtado

Reputation: 85

Spring JPA Repository: What is the best practice, use findAllById or iterate over IDs and call getReferenceById

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. Still, I doubt what is the better approach to achieve this.

I read some people saying that the repository.getReferenceById() throws an exception if the entity doesn't exist with the given ID and, if it exists, will load it in lazy mode. That's 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 this method returns a list where the entities are also loaded in lazy mode.

So, I want to know the best approach to fetch the entity's reference to associate it with another.

Some example code are below:

// 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 the first approach will result in only one query to fetch the entities, which may be better, and the second will perform N queries to fetch the entities, which I feel is worst.

Which one should I use?

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

Upvotes: 4

Views: 8971

Answers (1)

Toni
Toni

Reputation: 5105

I would suggest the second approach because the getReferenceById method calls the getReference method of the underlying EntityManager, which only instantiates and returns a proxy object using the provided primary key value, without querying the database.

The first approach is considered an anti-pattern when using it to reference entity associations since there is always an additional query executed.

For reference: FindById Anti-Pattern, How and when to use JPA’s getReference() Method

Upvotes: 4

Related Questions