Video in progress
Does adding one element to a large lazy collection (`post.getComments().add(c)`) load the whole collection?
It depends on the collection type. For a List (bag) on the mappedBy side, Hibernate queues the add() and doesn't load the collection. A Set has to check for duplicates, so it usually initializes the whole collection. size(), contains() and iteration always load it.
📖 Answer
The situation: the post has 50 thousand comments, and you're adding a new one.
@Transactional
public void addComment(Long postId, String text) {
Post post = posts.getReferenceById(postId);
post.getComments().add(new Comment(post, text)); // what gets loaded?
}
If comments is @OneToMany(mappedBy = "post") List<Comment>, Hibernate's PersistentBag, when not loaded, stores the add() as an "operation to apply later". The 50 thousand rows aren't read. With Set<Comment>, add() has to return true or false, and to know that, Hibernate loads the collection.
Another hidden load is a helper method that synchronizes the association on both sides:
public void addComment(Comment c) {
if (!comments.contains(c)) comments.add(c); // contains() loads everything
c.setPost(this);
}
In practice, for large collections I do it differently: I save from the child side and don't touch the parent's collection at all.
comments.save(new Comment(posts.getReferenceById(postId), text));
The FK is in comment.post_id, so the child is the owning side. The parent collection writes nothing to the database. If such collections only cause trouble, it's better to remove them from the mapping entirely and read the comments with a separate paginated query.
The old @LazyCollection(EXTRA) in Hibernate is deprecated, so don't rely on it in new code.
Sign up to mark studied questions and save your progress.