存储库模式:存储库可以使用其他存储库吗?
假设我有一个 TeacherRepository,需要根据下面的代码使用 CourseRepository。教师和课程形成多对多的关系。教师和课程不构成一个集合。您认为这种模式的正确使用吗?
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为处理课程是
TeacherRepository
的任务。恕我直言,最好在一个单独的类中处理这个问题。最好为每个类保留单一职责。更新
但是,如果您绝对想将此功能添加到
TeacherRepository
中,则可以在不依赖于CourseRepository
的情况下完成此操作: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 toCourseRepository
:我正在一个项目上做类似的事情,我没有看到你的方法有问题(并且不一定认为它与已发布答案的其他人的观点相矛盾)。
如果我有一个聚合根(教师),作为其聚合的一部分引用另一个聚合(课程),我认为该方法是有效的,原因如下:
我在这里没有看到这个问题,尽管随着我正在从事的项目的展开,我可能会获得更好的理解!
杰爱
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