resin-ee Many-to-Many CMP

Illustrates using many-to-many relations of EJB 3.0.

tutorial many2many
resin-web.xml configuration persistence.xml configuration The student bean The course bean The grade bean The course servlet

The many-to-many relation connects two tables with an association table. In the example, each Student takes several Courses. A grade_map table connects the two. Using the many-to-many relation, the application can return the student's courses or the students in a course.

CREATE TABLE Course ( course_id BIGINT PRIMARY KEY, name VARCHAR(255) ) CREATE TABLE Student ( student_id BIGINT PRIMARY KEY, name VARCHAR(255) ) CREATE TABLE grade_map ( id BIGINT PRIMARY KEY auto_increment, student_id BIGINT REFERENCES Student(student_id), course_id BIGINT REFERENCES Course(course_id) )

The Course has an @Id and a data column for the name.

@Entity public class Course { @Id @Column(name="course_id") public long getId() @Basic public String getName() }

The Student includes the many-to-many relation in its definition.

@Entity public class Student { @Id @Column(name="student_id") public long getId() @Basic public String getName() @ManyToMany(targetEntity="Course") @JoinTable( table=@Table(name="student_course_map"), joinColumns=@JoinColumn(name="student_id")", inverseJoinColumns=@JoinColumn(name="course_id")") public Collection getCourses() }

The @ManyToMany annotation marks a collection-valued field as a many-to-many relation. The targetEntity value specifies the target of the relation.

Since the many-to-many relation is a three-table relation, it needs to specify the association table as well as the columns.

private void doService(PrintWriter out) throws java.io.IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); Query allStudent = _entityManager.createQuery("SELECT o FROM Student o"); List students = allStudent.listResults(); for (int i = 0; i < students.size(); i++) { Student student = (Student) students.get(i); out.println("<h3>" + student.getName() + "</h3>"); Collection courses = student.getCourses(); out.println("<ul>"); Iterator iter = courses.iterator(); while (iter.hasNext()) { Course course = (Course) iter.next(); out.println("<li>" + course.getName()); } out.println("</ul>"); } } }