我有两个使用ManyToMany注释映射的实体,并且数据保存按预期工作,问题是我无法使多重选择显示正确的选定选项。
在我的模板中,我有:
<div class="form-select col-sm-10">
<select th:field="*{addresses}" class="form-control" multiple="multiple">
<option th:each="a : ${addresses}"
th:value="${a.addressId}" th:text="${a.addressName}">Opzione</option>
</select>
</div>
这与我用于单个选择的相同片段正确显示所选元素,但它不适用于多个。
ManyToMany注释以这种方式制作
@Entity
public class User {
@ManyToMany
private List<Address> addresses = new ArrayList<>();
//getters and setters
}
@Entity
public class Address {
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH, CascadeType.REFRESH}, mappedBy = "addresses")
private List<User> users = new ArrayList<>();
//getters and setters
}
在控制器中,我只需获取地址列表并将其添加到模型中。我看到select中的值,唯一不起作用的是选择正确的选项。 更多的是,如果我在编辑页面上选择一些新选项,它们会被正确保存
@RequestMapping("/{userId}")
public String getUser(@PathVariable long userId, ModelMap model) {
User logged = authenticationFacade.getAuthenticatedUser();
User user = service.findById(userId);
UserDTO dto = new UserDTO();
List<Location> locations = locationService.findAllLocations();
Iterable<Address> addresses = addressService.findByLocationInAndActiveIsTrue(locations);
List<Address> addressList = new ArrayList<>();
addresses.forEach(addressList::add);
logger.debug("Gli address dell'utente sono: " + user.getAddresses());
model.addAttribute("addresses", addressList);
model.addAttribute("user", dto);
model.addAttribute("edit", true);
model.addAttribute("pageTitle", user.getFirstName() + " " + user.getLastName());
model.addAttribute("userProfiles", userProfiles);
model.addAttribute("realUser", user);
return "admin/backuser";
}