Many-to-Many Mappings


Many-to-Many Mappings

A Set java collection with no duplicate elements may be used to construct a Many-to-Many mapping. We've previously seen how to map a Set collection in Hibernate, so if you know how to map a Set collection, you're ready to start with many-to-many mapping.

A Set is started using java.util.HashSet and mapped with a set> element in the mapping table. When there are no duplicate elements in the collection, you may utilize the Set collection in your class.

Consider the following scenario: We need to keep track of our employees in the EMPLOYEE table, which will have the following structure:

EMPLOYEE (id INT NOT NULL) is a table you may construct. PRIMARY KEY (id), auto increment, first name VARCHAR(20) default NULL, last name VARCHAR(20) default NULL, salary INT default NULL;

Assume that each employee can be linked with one or more certificates and that an equivalent certificate can be associated with many employees. Certificate-related data will be stored in a separate table with the following structure:

id INT NOT NULL auto increment, certificate name VARCHAR(30) default NULL, PRIMARY KEY (id) ; create table CERTIFICATE ( id INT NOT NULL auto increment, certificate name VARCHAR(30) default NULL, PRIMARY KEY (id) );

To build a many-to-many relationship between the EMPLOYEE and CERTIFICATE objects, we'll need to add another intermediary table with Employee ID and Certificate ID, as seen below.

create table EMP CERT ( employee id INT NOT NULL, certificate id INT NOT NULL, PRIMARY KEY (employee id,certificate id), PRIMARY KEY (employee id,certificate id), PRIMARY KEY (employee id,certificate id) );