Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form binding: relationship with intermediate entity (nested entity) - indirect Entity creation and binding

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).

like image 691
Leo Avatar asked Nov 02 '22 05:11

Leo


1 Answers

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;
}
like image 166
V G Avatar answered Nov 15 '22 04:11

V G