I have two services: TeacherService and PupilSerivce which are sharing the same database. The relationship between them is one-to-many that says one teacher can have many pupils and each pupil only has one teacher.
CREATE TABLE `test`.`teacher` {
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` varchar(40),
PRIMARY KEY (`id`)
} ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `test`.`pupil` {
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`teacher_id` bigint unsigned NOT NULL COMMENT 'teacher id',
PRIMARY KEY (`id`),
CONSTRAINT `fk_teacher_id` FOREIGN KEY (`teacher_id`) REFERENCES `teacher`(`id`) ON DELETE CASCADE
} ENGINE=InnoDB DEFAULT CHARSET=utf8;
as you can imagine, I have two entities TeacherVO and PupilVO that represents database table in my Java code.
the question is, both TeacherService and PupilSerivce run in individual process and communicate with messages, I don’t want they have any compilation dependency on each other. However, when adding a new pupile the method looks like:
PupilService.addNewPupil(long teacherId) {
if (isValidTeacher(teacherId) {
// add the pupile
}
}
this requires PupileService has knowledge of TeacherVO so it can do some validation, but TeacherVO is in TeacherService package!
What’s the best practice to remove such sort of dependency?
There are some ways I thought of:
-
create a validateTeacher message, then PupilService sends this message to TeacherService and wait for response. However, if I have further requirements like searching a teacher with name, then I have to create another message which at last results in message blowing up. Directly searching database is a more flexible and efficient way, but it introduces dependency.
-
don’t do any check and catch SQL exception caused by foreign key if the teacher_id is invalid. however, this can not solve the problem that I may have further requirements.
I think this should be a common issue in SOA architecture in case of multiple services share the same database. I did research a while but not get anything valuable.
I agree with Tony Hopkinson, what you’re trying to do is fundamentally unsound. You cannot separate the concerns of the teacher and student.