Let us consider the relation between Semester and Subjects. A Semester has a collection of Subjects. Each Subject, in turn, has a reference to the Semester.
This is illustrated as below:
public class Semester {
private Long semesterId;
private String semesterName;
private Set subjects;
...
}
public class Subject {
private Long subjectId;
private String subjectName;
private Semester semester;
...
}
This is how I convert it to Hibernate entities:
@Entity
public class Semester implements Serializable {
private static final long serialVersionUID = -6067841723974478563L;
@Id
@Column(name = "SEMESTER_ID")
@SequenceGenerator(name = "seq", allocationSize = 1, initialValue = 1, sequenceName = "SEQ_SEMESTER")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
private Long semesterId;
@Column(name = "SEMESTER_NAME")
private String semesterName;
@OneToMany(mappedBy = "semester", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set subjects;
...
}
@Entity
public class Subject implements Serializable {
private static final long serialVersionUID = 5705981176568667418L;
@Id
@Column(name = "SUBJECT_ID")
@SequenceGenerator(name = "seq", allocationSize = 1, initialValue = 1, sequenceName = "SEQ_SUBJECT")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
private Long subjectId;
@Column(name = "SUBJECT_NAME")
private String subjectName;
@ManyToOne
@JoinColumn(name = "SEMESTER_ID_FK")
private Semester semester;
...
}
Further, I should be able to insert it with the following code:
Set subjects = new HashSet();
Semester semester = new Semester();
for (int i = 1; i <; 5; i++) {
Subject subject = new Subject();
subject.setSubjectName("subject_" + i);
subject.setSemester(semester);
subjects.add(subject);
}
semester.setSemesterName("1st sem");
semester.setSubjects(subjects);
Transaction tr = session.beginTransaction();
session.save(semester);
tr.commit();
The SQL script is:
CREATE SEQUENCE SEQ_SEMESTER
START WITH 1
INCREMENT BY 1;
CREATE TABLE SEMESTER (
SEMESTER_ID NUMBER PRIMARY KEY NOT NULL,
SEMESTER_NAME VARCHAR(50) NOT NULL
);
CREATE SEQUENCE SEQ_SUBJECT
START WITH 1
INCREMENT BY 1;
CREATE TABLE SUBJECT (
SUBJECT_ID NUMBER PRIMARY KEY NOT NULL,
SUBJECT_NAME VARCHAR(50) NOT NULL,
SEMESTER_ID_FK NUMBER NOT NULL,
CONSTRAINT CNSTR_SEMESTER_ID_FK FOREIGN KEY(SEMESTER_ID_FK) REFERENCES SEMESTER(SEMESTER_ID)
);
The sources can be found https://github.com/paawak/blog/tree/master/code/OneToManyExample.