java - Hibernate two foreign keys on same table -
i have teacher entity has manytoone relationship on school. that's use case, teacher can join existing school, meaning school can have many teachers, there needs 1 owner, creator or admin of particular school.
@entity @primarykeyjoincolumn(name = "teacher_id", referencedcolumnname = "id") public class teacher extends user { @joincolumn(name = "school_id") @manytoone(fetch = fetchtype.eager) private school school;
school entity
@entity public class school extends baseentity { @onetomany(cascade = cascadetype.all, mappedby = "school") private set<teacher> teachers;
this works. proper way add owner column school entity. owner id of teacher created school. assigned once during creation of school.
so when adding new teacher choose create new school assigning name it. when school created assign same teacher persisted id owner created school.
adding onetoone on school entity seems work @ first, it's impossible break fk relationship between these 2 tables.
added school
@onetoone(cascade = cascadetype.all, orphanremoval = true) @joincolumn(name = "owner_teacher_id") private teacher owner;
for persisting doing this, , works current relationship, think it's wrong, there easier way set creator of record?
teacher savedteacher = teacherrepository.save(teacher); school savedschool = schoolservice.saveschool(school); savedteacher.setschool(savedschool); if (schoolform.isnewschool()) savedschool.setowner(savedteacher);
Comments
Post a Comment