1:n Relation (One to Many)

  1. Create an Automaker entity and add a company attribute of type String
  2. Close the Automaker tab and click Yes in the following dialog to save the Automaker entity.
  3. Create a Carmodel entity and add a model attribute of type String.
  4. Under Entities in the Project Manager, click Automaker.java and add the Automaker entity to the entity editor under Attributes.
  5. In the following dialog, choose the Many to One (n:1) option. 
  6. Apply the Bidirectional setting.
  7. Click OK.
  8. Click Save.
Result:
  • Entity Carmodel - The Carmodel entity is enhanced by the automaker entity of type Automaker.

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "automaker_id")
    public Automaker getAutomaker() {
    	return automaker;
    }
    
    public void setAutomaker(Automaker automaker) {
    	this.automaker = automaker;
    }


  • Entity Automaker -  By applying the setting Bidirectional, the Automaker entity, too, is enhanced with a list of all car models.

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "automaker")
    public List<Carmodel> getCarmodels() {
    	return carmodels;
    }
    
    public void setCarmodels(List<Carmodel> carmodels) {
    	this.carmodels = carmodels;
    }
    
    public Carmodel addCarmodel(Carmodel carmodel) {
    getCarmodels().add(carmodel);
    carmodel.setAutomaker(this);
    return carmodel;
    }
    
    public Carmodel removeCarmodel(Carmodel carmodel) {
    getCarmodels().remove(carmodel);
    carmodel.setAutomaker(null);
    return carmodel;
    }


Hinweis:
  • Relation in the code via annotation - In the code, the relation is defined with the annotation @ManyToOne or @OneToMany(mappedBy = "automaker").
  • Plural - For 1:n relations, RapidClipse automatically generates a plural name for the entity on the n-side, e.g. carmodels, to improve the readability.
  • Delete relation - To correctly delete a 1:n 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.