One To Many Example
Shows how to insert and select Student objects each with a list of Enrolled courses.
Student.java
public class Student
{
@Column(primaryKey=true)
int studentId;
String firstName;
String lastName;
Date graduationDate;
// studentId field establishes one to many relationship by default
// since it is same name in both Student and Entrolled classes
// use @OneToManyCascade to override defaults
List<Enrolled> enrollment;
getters/setters for studentId, firstName, lastName, graduationDate, and enrollment...
@Override
public String toString()
{
return studentId + " " + firstName + " " + lastName;
}
}
Enrolled.java
public class Enrolled
{
@Column(primaryKey=true)
int enrolledId;
int studentId;
int courseId;
int yr;
int semester;
getters/setters for enrolledId, studentId, courseId, yr, and semester...
@Override
public String toString()
{
return courseId + " " + yr + " " + semester;
}
}
Insert Three Students and Their Courses
ArrayList<Student> list = new ArrayList<>();
ArrayList<Enrolled> enrollment;
Student student;
// student John Miller
student = new Student();
student.setStudentId(9999);
student.setFirstName("John");
student.setLastName("Miller");
list.add(student);
// 1 course for John Miller
enrollment = new ArrayList<>();
enrollment.add(enroll202(student)); // creates Enrolled object for course 202
student.setEnrollment(enrollment);
// student John Smith
student = new Student();
student.setStudentId(8888);
student.setFirstName("John");
student.setLastName("Smith");
list.add(student);
// 2 courses for John Smith
enrollment = new ArrayList<>();
enrollment.add(enroll202(student)); // creates Enrolled object for course 202
enrollment.add(enroll601(student)); // creates Enrolled object for course 601
student.setEnrollment(enrollment);
// student Rita Miller
student = new Student();
student.setStudentId(7777);
student.setFirstName("Rita");
student.setLastName("Miller");
student.setGraduationDate(new GregorianCalendar(2000, 11, 31).getTime());
list.add(student);
// no courses for Rita Miller
// inserts 3 students and their enrolled objects
System.out.println(table.insertAll(list) + " rows inserted");
Output
Select Students and Their Courses
Database database = new Database(getConnection(), getSchema());
Table<Student> table = database.getTable(Student.class);
System.out.println("table.selectAll():");
for (Student s: table.selectAll())
{
System.out.println(s);
System.out.println(" enrolled:");
for (Enrolled e: s.getEnrollment())
{
System.out.println(" " + e);
}
}
Output
table.selectAll():
7777 Rita Miller
enrolled:
8888 John Smith
enrolled:
202 2011 1
601 2012 2
9999 John Miller
enrolled:
202 2011 1
See /src/examples/java/org/sormula/examples/cascade package in the project.
|