This is not a duplicate question. My question is a conceptual one rather than a coding one.
So I have 2 tables whose schema is given below:
create table classroom
(
building varchar(15),
room_number varchar(7),
capacity numeric(4, 0),
primary key (building, room_number)
);
create table section
(
course_id varchar(8),
sec_id varchar(8),
semester varchar(6)
check (semester in ('Fall', 'Winter', 'Spring', 'Summer')),
year numeric(4, 0) check (year > 1701 and year < 2100),
building varchar(15),
room_number varchar(7),
time_slot_id varchar(4),
primary key (course_id, sec_id, semester, year),
foreign key (course_id) references course (course_id)
on delete cascade,
foreign key (building, room_number) references classroom (building, room_number)
on delete set null
);
you can see that in section
table, 2 fields are foreign keys to 2 fields on another table. When modeling these in JPA, previous questions and answers point to create 2 one-many relations with 2 attributes on entity. Like this for example:
@IdClass(SectionId.class)
@Entity
@Table(name = "section")
public class Section {
@Id
private String courseId;
@Id
private String secId;
@Id
private String semester;
@Id
private Integer year;
private String building;
private String roomNumber;
private String timeSlotId;
// I'm only adding necessary parts of the table omitting getters, setters and other relationships
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JoinColumn(name = "building")
private Classroom classroomBuilding;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JoinColumn(name = "room_number")
private Classroom classroomNumber;
}
But unlike other examples, I don't need 2 different parameters on my entity to refer to the other table (entity). I only need a reference to "classroom" which is usually possible for a single foreign key. But here, because of 2 foreign keys, I had to create 2 parameters in entity.
So I though of this approach:
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JoinColumns(value = {
@JoinColumn(name = "building"),
@JoinColumn(name = "room_number")
})
private Classroom classroom;
This looks clear and concise. But I wonder will this approach work or not. And what particular benefits would I have if I opt in for the first approach?