I have one class named Question and another named StudentDriver. StudentDriver have a list of questions. Since both classes are aggregate roots they have their own repository.
When I am going to add a new question, should the StudentDriver class have a method named addQuestion()? And would I merge the studentdriver object through the studentdriver repository, or would I persist the question with the question repository? If I persist it with question repository then the list of questions belonging to a studentdriver would not contain the newly added question until I refresh it from the database.
I don’t understand the connection between the two aggregate root objects and how I am going to model it correctly.
I am using JPA.
Looks like you have two options:
1) Two aggregate roots. Adding new question would look like this:
And getting all questions for a student will be a responsibility of the questions repository:
Essentially you have a persistent unidirectional relationship from question to student: Question-belongs-to-StudentDriver (many-to-one).
2) One aggregate root. StudentDriver is a root of the aggregate that contains list of questions. Adding new question would look like this:
To get all questions for a student you would use something like:
The choice between two options depends on the information that is missing from the OP. Good way to identify aggregate root is to look at a lifecycle logic. Questions like