documentation examples changes amber (jpa) ejb database ioc jmx jsf messaging quercus remoting servlet security field property query many-to-one one-to-many many-to-many inherit sessions | links: the @manytoone relation
The Many-to-One link is the foundation of persistent relations. It links a source table to a destination with a database REFERENCES column. Many-to-One adds two capabilities: SQL extensions for links and direct lookup of target beans through field references.
Database SchemaA many-to-one relation links one table to another. In this example, each student entry links to the student's house. The database schema might look like: CREATE TABLE house ( id BIGINT PRIMARY KEY auto_increment, name VARCHAR(250), ) CREATE TABLE student ( id BIGINT PRIMARY KEY auto_increment, name VARCHAR(250), house BIGINT REFERENCES house(id) ) The House bean has two fields, @Entity public class House { @Id@Column(name="id") public long getId() @Basic public String getName() } The Student bean adds a many-to-one field, @Entity public class Student { @Id@Column(name="id") public long getId() @Basic public String getName() @ManyToOne@JoinColumn(name="house") public House getHouse() } @ManyToOne@ManyToOne marks the
field as a many-to-one field. The @JoinColumn@JoinColumn specifies the SQL column name and the target column for a many-to-one field. The default column name is the name of the many-to-one field. The default target column is the primary key of the target table. The many-to-one relation provides two capabilities to the client:
Query ExtensionsThe first relation capability extends SQL with relation paths
using the '.' operator like Java's field reference.
If The following example uses the extended SQL to return all students in a given house. private void doService(PrintWriter out) throws java.io.IOException { String sql = "SELECT s FROM Student s WHERE s.house.name=?1"; Query houseStudents = _entityManager.createQuery(sql); houseStudents.setParameter(1, "Gryffindor"); students = houseStudent.getResultList(); out.println("<h3>Gryffindor Students</h3>"); for (int i = 0; i < students.size(); i++) { Student student = (Student) students.get(i); out.println(student.getName() + "<br>"); } } Java ReferencesThe second relation capability returns a live, persistent bean through
the The example queries all students and prints their names and house names. private void doService(PrintWriter out) throws java.io.IOException { Query allStudent = _entityManager.createQuery("SELECT o FROM Student o"); List students = allStudent.getResultList(); for (int i = 0; i < students.size(); i++) { Student student = (Student) students.get(i); out.println(student.getName() + " lives in " + student.getHouse().getName() + "<br>"); } }
|