我有一个与Company
实体有ManyToMany
关联的Acknowledgement
实体。
@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;
...
}
在一个表单中,我希望能够选择一些应该绑定到Company
实体的确认(带有复选框)。因此,当我将带有 POST 的表单提交到我的控制器操作时,我的Company
对象包含许多Acknowledgement
对象。
我试图按照这个问题中的讨论更改为HashSet
,但没有运气。检查的对象将始终存在于我的数据库中,所以基本上我只需要为每个对象填充字段。TreeSet
Acknowledgement
id
这是我的控制器代码:
@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
}
}
还有我的 JSP 文件(查看)
<%@ 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>
我尝试了各种事情,上面就是其中之一,但我似乎无法弄清楚如何做到这一点。那么,如何Company
在提交表单时将选定的确认映射到我的实体中的关联?
非常感谢您!