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 😃
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
Answered By – birca123
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0