Search code examples
javajpaaggregateroot

JPA aggregate root approach


I'll use a blog post as an example.

The BlogPost entity is an aggregate root, and it contains a BlogPostComment collection. That's good because a post comment cannot exist without a parent blog post. Every operation on a BlogPostComment is taken care of by a BlogPost, or better by the service which manages BlogPost entities.

However, by taking this route, every time I want to add a comment, I'm forced to retrieve all the blog post information. Every time I want to remove a comment, I'm forced to retrieve all the blog post information. Etc.

So the first and most obvious solution would be to offer a separate service to operate on BlogPostComment(s). But that would violate the concept of a post comment. You shouldn't be able to operate on comments alone.

What's the right way to do this?


Solution

  • I think it's acceptable to split comments from articles as there could be a huge number of comments. If comments can be organised/rendered as threads then a thread might be a good aggregate root. A thread can then do things like compute the nested depth of comments to assist in rendering. That logic can then be in the ”smallest scope” of the thread and not part of the article object logic.

    Such things are design decisions. They may change as the model evolves. Breaking up the model into manageable pieces that can be worked with efficiently is a matter of working with the code and refactoring it when it becomes unwieldy