n:m Relation (Many to Many)
- Create a new Extra entity and add an extra attribute of type String.
- Close the Extra tab and click Yes in the following dialog to save the Extra entity.
- Create a new Car entity and add the following attributes:
- registration of type Date
- mileage of type Integer
- kw of type Integer
- price of type Double
- Under Entities in the Project Manager click Extra and add the Extra entity to the entity editor under Attributes.
- In the following dialog choose the Many to Many (n:m) option.
- Apply the Bidirectional setting and the proposed name carextra for the join table, which is required in the database for mapping the n: m relation.
- Click OK.
- Click Save.
Result:
Entity Car - The Car entity is enhanced with the extras attribute of type Set.
@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 extras; } public void setExtras(Set<Extra> extras) { this.extras = extras; }
Entity Extra - The Extra entity is enhanced with the cars entity 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 the code via annotation - In the code, the relation is defined in both entities with the annotation @ManyToMany.
- Plural - For n:m relations, RapidClipse automatically generates a plural name for the new attribute, e.g. Cars, to improve the readability.
- Delete relation - To correctly delete an n:m relation, you have to delete the corresponding attributes in both entities.
XDEV Software Corp. - One Embarcadero Center, San Francisco, CA 94111, US
Copyright © 2015. XDEV Software Corp. All rights reserved.