【spring实战第五版遇到的坑】3.1中的例子报错
按照书中的例子,一直做到第3.1章使用JDBC读写数据时,在提交设计的taco表单时,报了如下的异常信息:
Failed to convert property value of type java.lang.String to required type java.util.List for property ingredients; nested exception is java.lang.IllegalStateException: Cannot convert value of type java.lang.String to required type tacos.Ingredient for property ingredients[0]: no matching editors or conversion strategy found
异常的字面意思就是字符串的ingredients[0]
不能转换成tacos.Ingredient
,表单中的ingredients
是字符串当然不能自动的转换成tacos.Ingredient
对象,不过spring中是可以自定义转换器来进行转换的。
添加如下的转换器,将String
转换成tacos.Ingredient
就可以了:
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.findById(id);
}
}
不添加上面的转换器,即使在第3.2章使用Spring Data JPA持久化数据,提交的taco表单也不会报错,因为tacos.Ingredient
已经进行对象到数据库的映射,即使不配置如上的转换器 ,也能成功的提交表单。在这种情况下,spring在遇到要要将String转换成tacos.Ingredient
时,会认为这个字符串就是他的主键,会根据这个字符串id查找到该对象,并将其加入List
中。
作者:coder-qi
出处:https://www.cnblogs.com/coder-qi/p/10706765.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
· AES 加密模式演进:从 ECB、CBC 到 GCM 的 C# 深度实践
· InnoDB为什么不用跳表,Redis为什么不用B+树?
· 记一次 C# 平台调用中因非托管 union 类型导致的内存访问越界
· [EF Core]聊聊“复合”属性
· 那些被推迟的 C# 14 特性及其背后的故事
· 博客园出海记-开篇:扬帆启航
· 记一次 .NET 某汽车控制焊接软件 卡死分析
· 关于布尔类型的变量不要加 is 前缀,被网友们吐槽了,特来完善下
· C#中的多级缓存架构设计与实现深度解析
· 技术人日常避坑手册:高效工作,少踩坑