Video in progress
What's the difference between find() and getReference()?
find() goes to the database immediately and returns null if nothing is found. getReference() returns a proxy without a SELECT. The database is read only when you touch a field of the proxy, and if the row doesn't exist, that's when EntityNotFoundException is thrown.
📖 Answer
getReference() is most useful for setting a foreign key:
@Transactional
public void addComment(Long postId, String text) {
Post post = em.getReference(Post.class, postId); // no SELECT
em.persist(new Comment(post, text)); // just the INSERT
}
Here we don't need the post's fields, only its id. With find we'd send a needless SELECT.
In Spring Data the same thing is getReferenceById() (the old name getOne() is deprecated).
Things to watch out for:
- if the post doesn't exist in the database, the error shows up at INSERT time as a foreign key violation, much later;
- if you take the proxy outside the transaction and touch its fields, you get
LazyInitializationException; - if the entity is already in the context, both methods return that same ready object.
Sign up to mark studied questions and save your progress.