| ||||||||||||||||||||||||||||||
Find this tutorial in: /usr/local/resin/webapps/resin-doc/amber/tutorial/cmp-many2one
Try the Tutorial 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:
The House bean has two fields, and , to model the house columns. House annotates getId with @Id to mark it as a primary key. It annotates getName with @Basic to mark it as a data column.
The Student bean adds a many-to-one field, to the and columns. It marks the getHouse getter with @ManyToOne to mark it as a many-to-one column.
@ManyToOne@ManyToOne marks the field as a many-to-one field. The @ManyToOne annotation can also specify the target bean. By default, the field's type determines the target bean. @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 s is a student, then s.house is the student's house and s.house.name is the name of the student's house. Resin translates the extended SQL to plain SQL automatically. The following example uses the extended SQL to return all students in a given house.
Java ReferencesThe second relation capability returns a live, persistent bean through the getHouse() method. Amber will perform any necessary database lookup. The example queries all students and prints their names and house names.
|