1:n Relation (One to Many)

  1. Create an entity CarManufacturer and add an attribute company of type String.

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

  3. Create an entity Car and add an attribute model of type String.

  4. In the Project Manager, click main-java > domain > CarManufacturer.java and drag it to the Attributes area in the Entity Editor.

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

  6. Accept the Bidirectional setting.

  7. Click OK.

  8. Click Save.

    Image not found

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;
    }

    Image not found

  • 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;
    }
  • 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.