n:m Relation (Many to Many)

  1. Create a new entity Extra and add an attribute extra of type String.

  2. Close the Extra tab and click Yes in the following dialog to save the Extra entity.

  3. Create a new entity Car and add the following attributes:

    1. registration of type date.

    2. mileage of type Integer.

    3. kw of type Integer.

    4. price of the type *double

  4. In the Project Manager at *main-java > domain click on Extra.java and drag it to the Attributes field in the entity editor.

  5. In the following dialog, select the Many to Many (n:m) option.

  6. Accept the setting Bidirectional and the suggested name carextra for the join table needed in the database for mapping the n:m relation.

  7. Click OK.

  8. Click Save.
    Image not found

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.

+ Image not found

+

@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.