1:n Relation (One to Many)
-
Create an entity CarManufacturer and add an attribute company of type String.
-
Close the CarManufacturer tab and click Yes in the following dialog to save the entity.
-
Create an entity Car and add an attribute model of type String.
-
In the Project Manager, click main-java > domain > CarManufacturer.java and drag it to the Attributes area in the Entity Editor.
-
In the following dialog, select the Many to One (n:1) option.
-
Accept the Bidirectional setting.
-
Click OK.
-
Click Save.
Result:
Entity Car - The Car entity is extended by the carManufacturer attribute of type CarManufacturer.
+
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "carManufacturer_id")
public CarManufacturer getCarManufacturer()
{
return this.carManufacturer;
}
public void setCarManufacturer(final CarManufacturer carManufacturer)
{
this.carManufacturer = carManufacturer;
}
Entity CarManufacturer - By the adopted setting Bidirectional the entity CarManufacturer is simultaneously extended by a list with all cars.
+
@OneToMany(fetch = FetchType.LAZY, mappedBy = "carManufacturer")
public List<Car> getCars()
{
return this.cars;
}
public void setCars(final List<Car> cars)
{
this.cars = cars;
}
public Car addCar(final Car car)
{
this.getCars().add(car);
car.setCarManufacturer(this);
return car;
}
public Car removeCar(final Car car)
{
this.getCars().remove(car);
car.setCarManufacturer(null);
return car;
}
Note:
Relation in code by annotation - In the code the relation is defined with the help of the annotations @ManyToOne, respectively @OneToMany(mappedBy = "carManufacturer"). * Plural - For 1:n relations RapidClipse automatically converts the entity name on the n side to plural for better readability, e.g. cars. * Delete relation - To correctly delete a bidirectional relation, you must delete the corresponding attributes in both entities.