Я создаю простое приложение для рецептов (как проект для курса), используя SpringBoot + Thymeleaf. Моя модель имеет классы рецептов и категорий с отношением «многие ко многим». То, что я пытаюсь сделать sh, это добавить флажок в форму обновления рецепта для выбора одной или нескольких категорий и сохранения их в рецепте. Категории извлекаются из БД.
Отображение соответствующих частей кода ниже.
Это объект команды :
@Getter
@Setter
@NoArgsConstructor
public class RecipeCommand {
private Set<CategoryCommand> categories = new HashSet<>();
}
Контроллер:
@Autowired CategoryService categoryService;
@GetMapping("recipe/{id}/update")
public String updateRecipe(@PathVariable String id, Model model) {
model.addAttribute("recipe", recipeService.findCommandById(Long.valueOf(id)));
model.addAttribute("foundCategories", categoryService.findAll());
return "recipe/recipeform";
}
@PostMapping("recipe")
public String saveOrUpate(@Valid @ModelAttribute("recipe") RecipeCommand command, BindingResult bindingResult) {
RecipeCommand savedCommand = recipeService.saveRecipeCommand(command);
if(bindingResult.hasErrors()){
bindingResult.getAllErrors().forEach(objectError -> {
log.debug(objectError.toString());
});
return RECIPE_RECIPEFORM_URL;
}
return "redirect:/recipe/" + savedCommand.getId() + "/show";
}
HTML (это не работает вообще):
<ul class="checkbox-list">
<li th:each="foundCategory : ${foundCategories}">
<input type="checkbox" th:field="${recipe.categories.add()}" th:value="${foundCategory}"/>
<label th:for="${foundCategory.getDescription()}"th:text="${foundCategory.getDescription()}"> </label>
</li>
В этой текущей итерации моего кода выдается эта ошибка:
org.springframework.beans.NotReadablePropertyException: Invalid property 'categories.add()' of bean class [cursospring.recipeapp.commands.RecipeCommand]: Bean property 'categories.add()' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Просто чтобы было понятно, я понимаю, почему я получаю эту ошибку, просто я не нашел способ сделать так, чтобы это работало, и это моя последняя попытка (и я сейчас пытаюсь сделать что угодно).
Итак, повторюсь, я пытаюсь сохранить выбранные флажки в наборе. это поле объекта, который я обновляю через POST.