[英]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.
对每个班级保持单一责任更好。
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: 如果我有一个聚合根(教师)作为其聚合的一部分引用另一个聚合(课程),我认为该方法是有效的,原因如下:
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.