简体   繁体   English

存储库模式:存储库可以使用其他存储库吗?

[英]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. 假设我有一个TeacherRepository需要根据下面的代码使用CourseRepository。 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. 我认为处理课程TeacherRepository的任务。 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 : 但是,如果您绝对想要将此功能添加到TeacherRepository ,则可以在不依赖于CourseRepository情况下执行此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 每个存储库仍然负责其自己的聚合根的CRUD操作
  2. It is still possible to create instances of the each Aggregate through the API of each repository 仍然可以通过每个存储库的API创建每个聚合的实例
  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 JLove

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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