I have a rather unique situation when trying to map a single table to multiple objects in JPA. I read about @Embeddable and @ElementCollection, but I'm not sure how to use them in my situation (or, if possible). One database table contains course information. The table may contain rows in which everything in the course is the same, with the exception of several values, such as room number and day. For instance:
TERM_CODE SUBJECT_CODE ROOM DAY INSTRUCTOR_ID
201220 EGRE 0101 TR 123
201220 EGRE 0103 W 124
Is there a way in which I can extract data from two rows, as described above, and put the general data in one object and different values in the Collection of separate objects? Here is an example of how I would like to define classes:
@Entity
public class Course implements Serializable {
@Id
@Column(name = "TERM_CODE")
private Long termCode;
@Column(name = "SUBJECT_CODE")
private String subjectCode;
@Embedded
Collection<CourseSchedule> schedule;
public Long getTermCode() {
return termCode;
}
public void setTermCode(Long termCode) {
this.termCode = termCode;
}
public String getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(String subjectCode) {
this.subjectCode = subjectCode;
}
}
CourseSchedule:
@Embeddable
public class CourseSchedule {
private String room;
private String day;
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getInstructorId() {
return instructorId;
}
public void setInstructorId(String instructorId) {
this.instructorId = instructorId;
}
}
I am also confused about what my JPQL will look like in this situation as soon as I have matched them.
EDIT:
@Id TERM_CODE, Course Hibernate, CourseSchedule, , null.
2:
Course CourseSchedule ( ), @OneToMany @ManyToOne.
@Entity
@IdClass(CourseId.class)
@Table(name = "course_table")
public class Course implements Serializable {
@OneToMany(mappedBy = "course")
private Collection<CourseSchedule> schedule;
@Id
@Column(name = "TERM_CODE")
private Long termCode;
@Id
@Column(name = "SUBJECT_CODE")
private Long subjectCode;
...
}
@Entity
@IdClass(CourseScheduleId.class)
@Table(name = "course_table")
public class CourseSchedule implements Serializable {
@ManyToOne
@JoinColumns({
@JoinColumn(name="TERM_CODE", referencedColumnName="TERM_CODE"),
@JoinColumn(name = "SUBJECT_CODE", referencedColumnName="SUBJECT_CODE")
})
private Course course;
@Column(name = "TERM_CODE")
private Long termCode;
@Column(name = "SUBJECT_CODE")
private Long subjectCode;
@Id
private String room;
@Id
private String day;
@Id
@Column(name = "INSTRUCTOR_ID")
private String instructorId;
...
}
(CourseId CourseScheduleId , ID.) :
org.hibernate.MappingException: Foreign key (FK82D03688F590EF27:course_table [TERM_CODE,SUBJECT_CODE])) must have same number of columns as the referenced primary key (course_table [ROOM,DAY,INSTRUCTOR_ID)
CourseSchedule, , .
? , ( ), - JPQL.