n:m Relation (Many to Many)

  1. Create a new Extra entity and add an extra attribute of type String.
  2. Close the Extra tab and click Yes in the following dialog to save the Extra entity.
  3. Create a new Car entity and add the following attributes:
    1. registration of type Date 
    2. mileage of type Integer
    3. kw of type Integer
    4. price of type Double
  4. Under Entities in the Project Manager click Extra and add the Extra entity to the entity editor under Attributes.
  5. In the following dialog choose the Many to Many (n:m) option.
  6. 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.
  7. Click OK.
  8. 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.