Java Reference
In-Depth Information
Associations can be implemented as unidirectional or bidirectional depending upon how they are
being used and navigated. A unidirectional association always navigates from a parent object (own-
ing side) to a child object (inverse side), whereas in a bidirectional association, both directions of
navigation are supported. Depending upon the multiplicity, the association can then be qualified
using the following annotations: @OnetoMany , @ManytoOne , or @ManytoMany . An example of map-
ping a unidirectional many-to-many relationship in Hibernate follows.
Many-to-Many relationship Mapping Using hibernate 
try it out
In this example, you perform a many-to-many mapping using annotations in Hibernate.
1.
Start by creating a new table called project in MySQL. The table has two attributes— ProjectID
is the primary key and PName contains the name of the project. The SQL DDL for the project table
is as follows:
CREATE TABLE 'project' (
'ProjectID' int(11) NOT NULL,
'PName' varchar(45) DEFAULT NULL,
PRIMARY KEY ('ProjectID')
) ENGINE=InnoDB DEFAULT CHARSET = utf8;
2.
Now assume that there is a many-to-many relationship between the tables employee and project .
In other words, an employee can work on at least 0 and at most m projects, whereas a project is
assigned to at least 0 and at most n employees. This can be visualized in an Entity Relationship
(ER) diagram, as shown in Figure 9-17.
0...n
0...m
Employee
Project
figure 9-17  
3.
In order to implement this many-to-many relationship in MySQL, create a new table called works_
on as follows:
CREATE TABLE 'works_on' (
'EmployeeID' int(11) NOT NULL,
'ProjectID' int(11) NOT NULL,
PRIMARY KEY ('EmployeeID','ProjectID'),
KEY 'works_onProj_idx' ('ProjectID'),
CONSTRAINT 'works_onEmp' FOREIGN KEY ('EmployeeID')
REFERENCES 'employee' ('EmployeeID')
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT 'works_onProj' FOREIGN KEY ('ProjectID')
REFERENCES 'project' ('ProjectID')
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
The works_on table has two attributes— EmployeeID and ProjectID —which make up the pri-
mary key and are at the same time foreign keys referring to the primary keys of the Employee and
Project tables, respectively.
 
Search WWH ::




Custom Search