I'm building an application using Hibernate. I work with a database schema that contains (amongst others) two tables called assignment and assignment_type. The latter contains primary key / value pairs that describe the type of the assignment (e.g. "written", "practical").
assignment, however, is an abstract class extended by such classes as written_assignment and practical_assignment. For this I'm using the class table inheritance approach (some details on the topic).
Now, it would make sense to set a reference to the appropriate object in the assignment_type during the creation of instances of classes like written_assignment, something like this:
public WrittenAssignment() {
AssignmentType assignmentType = ...; // Create or acquire appropriate instance
this.setAssignmentType(assignmentType);
}
As far as I understand it, going with the "create instance" approach will only work once, that one time being the state when there is no object in the database yet with that value (since the value of the assignment_type table is set to be unique).
Is there a way to set a reference to an object from assignment_type in the constructor of WrittenAssignment without acquiring it first? Bonus question: can it be created if no matching object exists yet?