n:m Relation (Many to Many)
-
Create a new entity Extra and add an attribute extra of type String.
-
Close the Extra tab and click Yes in the following dialog to save the Extra entity.
-
Create a new entity Car and add the following attributes:
-
registration of type date.
-
mileage of type Integer.
-
kw of type Integer.
-
price of the type *double
-
-
In the Project Manager at *main-java > domain click on Extra.java and drag it to the Attributes field in the entity editor.
-
In the following dialog, select the Many to Many (n:m) option.
-
Accept the setting Bidirectional and the suggested name carextra for the join table needed in the database for mapping the n:m relation.
-
Click OK.
-
Click Save.
Result:
Entity Car - The Car entity is extended by the extras attribute of the Set type.
+
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "carextra", joinColumns = @JoinColumn(name = "Car_id", referencedColumnName = "id", nullable = false, updatable = false), inverseJoinColumns = @JoinColumn(name = "Extra_id", referencedColumnName = "id", nullable = false, updatable = false))
public Set<Extra> getExtras()
{
return this.extras;
}
public void setExtras(final Set<Extra> extras)
{
this.extras = extras;
}
Entity Extra - The entity Extra is extended by the attribute cars of type Set.
+
+
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "carextra", joinColumns = @JoinColumn(name = "Extra_id", referencedColumnName = "id", nullable = false, updatable = false), inverseJoinColumns = @JoinColumn(name = "Car_id", referencedColumnName = "id", nullable = false, updatable = false))
public Set<Car> getCars()
{
return cars;
}
public void setCars(Set<Car> cars)
{
this.cars = cars;
}
Note:
-
Relation in code by annotation - In the code, the relation in both entities is defined using the annotation @ManyToMany.
-
Plural - For n:m relations RapidClipse automatically creates the name of the new attribute in plural for better readability, e.g. cars.
-
Delete relation - To correctly delete a bidirectional relation, you must delete the corresponding attributes in both entities.