I have a Company
entity that has a ManyToMany
association with an Acknowledgement
entity.
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "company_acknowledgement", joinColumns = @JoinColumn(name = "company_id"), inverseJoinColumns = @JoinColumn(name = "acknowledgement_id"))
@OrderBy("name")
private Set<Acknowledgement> acknowledgements = new HashSet<>();
...
}
@Entity
public class Acknowledgement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@Column(length = 50, nullable = false)
private String name;
...
}
Within a form, I want to be able to choose a number of acknowledgements that should be bound to the Company
entity (with checkboxes). So when I submit the form with POST to my controller action, my Company
object contains a number of Acknowledgement
objects.
I tried to change the HashSet
to TreeSet
as discussed in this question, but without luck. The checked Acknowledgement
objects will always exist in my database, so basically I only need to populate the id
field for each object.
Here is my controller code:
@Controller
public class CompanyController {
@Autowired
private CompanyService companyService;
@RequestMapping("/company/edit/{companyId}")
public String edit(Model model, @PathVariable int companyId) {
Company company = this.companyService.get(companyId);
model.addAttribute("company", company);
return "company-edit";
}
@RequestMapping(value = "/company/edit", method = RequestMethod.POST)
public String doEdit(Model model, Company company) {
return ""; // TODO: persist company
}
}
And my JSP file (view)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:url var="actionUrl" value="/company/edit" />
<form:form action="${actionUrl}" commandName="company">
<form:label path="name">Name:</form:label>
<form:input path="name" />
<%-- Other inputs here --%>
<input type="checkbox" name="acknowledgements[]" value="1" />
<input type="checkbox" name="acknowledgements[]" value="2" />
<form:button>Save Changes</form:button>
</form:form>
I tried various things, the above being one of them, but I cannot seem to figure out how to do this. So, how do I map the selected acknowledgements to the the association in my Company
entity when submitting the form?
Thank you very much in advance!