thymeleaf 无法将 java.lang.String 类型的属性值转换为所需的 java.util.List 类型 [英] thymeleaf Failed to convert property value of type java.lang.String to required type java.util.List
问题描述
我是 Spring 和 Spring Boot 的新手,正在阅读一本充满缺失信息的书.
I am new to Spring and Spring Boot and am working through a book that is full of missing information.
我有一个炸玉米饼课:
public class Taco {
...
@Size(min=1, message="You must choose at least 1 ingredient")
private List<Ingredient> ingredients;
...
}
正如你所看到的 ingredients
是 List
类型,这就是问题所在,它曾经是 List
类型code> 但那是在我开始在数据库中保存数据之前,现在它必须是 List
打破了整个事情.
As you can see ingredients
is of type List<Ingredient>
and that is the problem, it used to be of type List<String>
but that was before I started saving data in the database, now it must be List<Ingredient>
which breaks the whole thing.
在控制器中,我有以下内容(除其他外,我认为这是解决手头问题唯一需要的代码,但如果您需要更多,请告诉我):
In the contoller I have the following (among other things, I think this is the only required code for the problem at hand but if you need more let me know):
@ModelAttribute
public void addIngredientsToModel(Model model) {
List<Ingredient> ingredients = new ArrayList<>();
ingredientRepo.findAll().forEach(i -> ingredients.add(i));
Type[] types = Ingredient.Type.values();
for (Type type : types) {
model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
}
}
private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type) {
return ingredients
.stream()
.filter(x -> x.getType()
.equals(type))
.collect(Collectors.toList());
}
最后在我的百里香文件中:
And finally in my thymeleaf file I have:
<span class="text-danger"
th:if="${#fields.hasErrors('ingredients')}"
th:errors="*{ingredients}">
</span>
导致错误的原因:
thymeleaf Failed to convert property value of type java.lang.String to required type java.util.List
再次,当private List
是 private List
它起作用了,但现在它必须是private List
因为它在数据库中的保存方式,但此时它坏了,如何修复它?
Once again, when private List<Ingredient> ingredients;
was private List<String> ingredients;
it worked, but now it must be private List<Ingredient> ingredients;
because of the way it is saved in the database but it breaks at this point, how to fix it?
推荐答案
我遇到了同样的问题,我们需要一个转换器.
I met the same problem, what we need here is a converter.
package tacos.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import tacos.Ingredient;
import tacos.data.IngredientRepository;
@Component
public class IngredientByIdConverter implements Converter<String, Ingredient> {
private IngredientRepository ingredientRepo;
@Autowired
public IngredientByIdConverter(IngredientRepository ingredientRepo) {
this.ingredientRepo = ingredientRepo;
}
@Override
public Ingredient convert(String id) {
return ingredientRepo.findOne(id);
}
}
这篇关于thymeleaf 无法将 java.lang.String 类型的属性值转换为所需的 java.util.List 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!