Repository pattern: Can a repository use other repositories?
Suppose I have a TeacherRepository that needs to make use of a CourseRepository per the code below. Teacher and Course form a many to many relationship. Teacher and Course do not form an aggregate. Would you consider this proper use of the pattern?
class TeacherRepository {
@Inject(@Named("courseRepository"))
private final CourseRepository courseRepository;
public void addCourseToTeachers(String courseName) {
Course course = courseRep开发者_StackOverflowository.findByName(courseName);
for (Teacher teacher : readAll())
teacher.addCourse(course);
}
}
I don't think it is the task of the TeacherRepository
to deal with courses. IMHO it would be better to handle this in a separate class. It is better to keep a single responsibility for every class.
Update
But if you absolutely want to add this functionality to TeacherRepository
, you can do it without any dependency to CourseRepository
:
class TeacherRepository {
public void addCourseToTeachers(Course course) {
for (Teacher teacher : readAll())
teacher.addCourse(course);
}
}
...
CourseRepository courseRepository = ...;
TeacherRepository teacherRepository = ...;
...
Course course = courseRepository.findByName(courseName);
if (course != null)
teacherRepository.addCourseToTeachers(course);
I'm doing something similar on a project and I don't see the problem in your approach (and don't necessarily believe it contradicts the views of others who have posted answers).
If I have one Aggregate Root (Teacher) which as part of it's aggregate references another aggregate (Course), I think the approach is valid for the following reasons:
- Each repository is still responsible for CRUD operations of it's own aggregate root
- It is still possible to create instances of the each Aggregate through the API of each repository
- The Teacher repository still has one responsibility (To create a Teacher aggregate). It just happens that you cannot create a Teacher without the Teacher containing a reference to the taught courses.
I don't see the issue here although I may gain a better understanding as the project I'm working on unfolds!!.
JLove
精彩评论