My simplified model looks like this:
@Entity public class Aspect extends Model {
@Id public Long id;
@OneToMany(cascade = CascadeType.ALL) public List<Restriction> restrictions;
}
@Entity public class Restriction extends Model {
@Id public Integer id;
@ManyToOne public RestrictionTemplate restrictionTemplate;
}
@Entity public class RestrictionTemplate extends Model {
@Id private Integer id;
}
Basically the idea is this: each Aspect has a set of Restrictions. And each Restriction itself relies on a RestrictionTemplate.
I want Aspect creation form to like this: user can select some RestrictionTemplates and on form submit new Restrictions should be created and associated with new Aspect.
Let me explain once again: On form submission I want to create Aspect and relating Restrictions based on RestrictionTemplate's ids provided.
Whicn names should the fields in the form have in order to make such binding possible?
The naming which works for direct relantionships:
restrictions[0].restrictionTemplate.id
restrictions[1].restrictionTemplate.id
doesn't work here (creates Aspect entry in DB, but no Restriction entries).
I think you simply must write a bit of code for that, in which you search for the RestrictionTemplates
corresponding to the passed IDs and then assigning them to the new instance of Aspect
:
List<RestrictionTemplates> templates = new ArrayList<RestrictionTemplates>();
for (int crtTplId : passedIds) {
templates.add(entityManager.find(RestrictionTemplates.class, crtTplId));
}
List<Restriction> restrictions = new ArrayList<Restriction>();
for (RestrictionTemplates crtTpl : templates) {
restrictions.add(new Restriction(crtTpl));
}
Aspect aspect = new Aspect();
aspect.restrictions = restrictions;
entityManager.persist(aspect);
PS: as I understand, there can be Restrictions that do not belong to an Aspect. If that is not true, than you should make your Aspect-Restriction relationship bilateral, Restriction
being the owning side:
@Entity public class Aspect extends Model {
@Id public Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy="aspect") public List<Restriction> restrictions;
}
@Entity public class Restriction extends Model {
@Id public Integer id;
@OneToMany(/*+ add the @JoinColumn for marking the column not nullable*/) public Aspect aspect;
@ManyToOne public RestrictionTemplate restrictionTemplate;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With