I am using Hibernate and have two tables, STUDENTS and DORM_ROOMS, that are related with a composite key:
Code:
STUDENTS table:
CAMPUS(String) Part of Composite Key
STUDENT_ID (int) Part of Composite Key
NAME (String)
...
DORM_ROOMS table:
CAMPUS(String) Part of Composite Key
STUDENT_ID (int) Part of Composite Key
ROOM_NUMBER(int)
...
The relationship is one to one because a student can be associated with exactly one dorm room and and a dorm room is associated with one student (wow - a private room!). However, not all students have a dorm room.
My initial code (stripped down) looks like:
Code:
FOR STUDENTS:
@Embeddable
public class StudentsPK implements Serializable {
@Column(name = "CAMPUS")
private String Campus;
@Column(name = "STUDENT_ID")
private String StudentID;
...
}
@Entity
@Table(name = "STUDENTS")
public class Students implements Serializable {
@EmbeddedId
private StudentsPK studentsPK;
...
}
FOR DORM_ROOMS:
@Embeddable
public class DormRoomsPK implements Serializable {
@Column(name = "CAMPUS")
private String Campus;
@Column(name = "STUDENT_ID")
private String StudentID;
...
}
@Entity
@Table(name = "DORM_ROOMS")
public class DormRooms implements Serializable {
@EmbeddedId
private DormRoomsPK dormRoomsPK;
...
}
Assume that the database schema is already defined and created. In particular, CAMPUS+STUDENT_ID is a PK for STUDENTS and CAMPUS+STUDENT_ID is a FK for DORM_ROOMS that serves as the PK in that table. At this point I can successfully insert a row into STUDENTS and a row into DORM_ROOMS. I can also retrieve any student from STUDENTS even if the student does not have a dorm room. However, I have not yet "informed" Hibernate about the relationship between the two tables. That is where I am confused.
I tried to "relate" the two tables by using a "JOIN" annotation but I discovered that this causes any attempt to fetch a student that has no dorm room to return an empty result set. I suppose that makes since if "JOIN" states that the tables are to always be viewed as joined then joining a student having no dorm room with no matching rows in the DORM_ROOMS table would result in an empty result set.
Since using a "JOIN" annotation doesn't work, how do I modify my code to describe the relationship between the two tables but still allow me to fetch students that have no matching dorm rooms?
Thank you.