How to persist n:n releated entities programmatically

How to set and persist a n:n relation?
E.g.:
Car car= metadata.create(Car.class);
car.getInstalledSystems().Add(…) // this doesnt work because the related set (InstalledSystems) is Null

Must the releated entities set be instantiated (e.g. by calling setInstalledSystems(…))? How to persist the relations with entitymanager?

Yes, when creating to-many associations programmatically (not using client-tier datasources), you should instantiate collections:


Car car = metadata.create(Car.class);
car.setInstalledSystems(new HashSet());
car.getInstalledSystems().add(x);
car.getInstalledSystems().add(y);
car.getInstalledSystems().add(z);
persistence.getEntityManager().persist(car);

The relation will be saved together with car if the car entity has an owning side of relation (for many-to-many relations generated by Studio both sides are owning). The x,y,x instances should be either detached (already exist in the database), or persisted in the same transaction.