|
| |
Find this tutorial in: /usr/local/resin/webapps/resin-doc/amber/tutorial/cmp-many2many
Try the Tutorial
Illustrates using many-to-many relations of EJB 3.0.
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.
SQL Schema
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.
Course.java
@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.
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.
ManyToManyServlet.java
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>");
}
}
}
|
Try the Tutorial
Copyright © 1998-2006 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark,
and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc. | |
|