I’m looking for a solution to manage a one-to-many relation within an HTML form using jQuery. I’m developing with Spring, Spring MVC and Hibernate. I found many tracks on the web, but not any working full-example.
The background
I’ve three JPA entities:
Consult.java (1)
@Entity
@Table(name = "consult")
public class Consult
private Integer id;
private String label;
private Set<ConsultTechno> consultTechnos;
/* getters & setters */
}
ConsultTechno.java (2)
@Entity
@Table(name = "consult_techno")
public class ConsultTechno {
private Integer id;
private Techno techno;
private Consult consult;
private String level;
/* getters & setters */
}
Techno.java (3)
@Entity
@Table(name="techno")
public class Techno {
private Integer id;
private String label;
private Set<ConsultTechno> consultTechnos;
/* getters & setters */
}
As shown, a Consult (1) contains n ConsultTechnos (2), which are caracterized by a level and a Techno (3).
The needs
Using an HTML form, I would like to have a Add a techno button which dynamically adds two fields in the DOM:
<input type="text" name="consult.consultTechnos[].techno.id" />
<input type="text" name="consult.consultTechnos[].level" />
Of course, each time the user clicks on the button, those two fields should be re-added, etc. I chose input type="text" for the example, but at the end, the fields will be two select.
Four kinds of operation should be covered:
- Add a child entity when creating a new master entity
- Remove a child entity when creating a new master entity
- Add a child entity when updating a new master entity
- Remove a child entity when updating a new master entity
The problem
That layout part already works, but when posting the form, I can’t manage to bind the dynamically added fields to my @ModelAttribute consult.
Do you have any idea of how to do that kind of jobs? I hope I’ve been clear enough…
Thanks in advance :)
This point is still quite confusing and unclear on the web, so here is the way I solved my problem. This solution is probably not the most optimized one, but it works when creating and updating a master entity.
Theory
Use a
Listinstead of aSetfor your one-to-many relations which should be dynamically managed.Initialize your
Listas anAutoPopulatingList. It’s a lazy list which allows to add dynamically elements.Add an attribute
removeofintto your child entity. This will play the part of a boolean flag and will be usefull when removing dynamically an element.When posting the form, persist only the elements that have the flag
removeon0(i.e.false).Practice
A working full-example: an employer has many employees, an employee has one employer.
Entities:
Employer.javaEmployee.javaController:
EmployerController.javaView:
employer/edit.jspHope that could help
:)