Video in progress
What is the difference between findById and getReferenceById?
findById reads from the database and returns an Optional, empty if there's no record. getReferenceById gives you a proxy without a SELECT, and only goes to the database when you touch a field; if the record doesn't exist, EntityNotFoundException is thrown at that point.
📖 Answer
// 1) You need the data: findById
User user = userRepo.findById(id)
.orElseThrow(() -> new NotFoundException("user " + id));
mail.send(user.getEmail());
// 2) You only need the id for a relationship: getReferenceById
Comment c = new Comment();
c.setText(text);
c.setAuthor(userRepo.getReferenceById(authorId)); // no SELECT
commentRepo.save(c); // only an INSERT
In the second case we don't need the author's name, only a reference for the author_id FK. With findById there would be a pointless SELECT.
findById |
getReferenceById |
|
|---|---|---|
| SELECT | immediately (unless it's already in the persistence context) | when a field is touched |
| If not found | Optional.empty() |
EntityNotFoundException later |
| Returns | the real entity | a Hibernate proxy |
The trap: if you use the result of getReferenceById outside a transaction, you get LazyInitializationException. Where you need to check that the record exists (for example, the client sent the id through the API), use findById, otherwise the error shows up late and in a confusing place.
Note: this method used to be called getOne() and getById(); both are deprecated.
Sign up to mark studied questions and save your progress.