简体   繁体   中英

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 = courseRepository.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:

  1. Each repository is still responsible for CRUD operations of it's own aggregate root
  2. It is still possible to create instances of the each Aggregate through the API of each repository
  3. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM