【spring实战】报错 Cannot convert value of type java.lang.String to required type tacos.Ingredient f解决

1 篇文章 0 订阅
1 篇文章 0 订阅

转【spring实战第五版遇到的坑】3.1中的例子报错

https://www.cnblogs.com/zhangfengxian/p/10706765.html

按照书中的例子,一直做到第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 com.itcast.converter;

import com.itcast.dao.IngredientDao;
import com.itcast.pojo.Ingredient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

/**
 * @program: tacocloud
 * @description: 转换器     解决错误 Cannot convert value of type 'java.lang.String' to required type 'com.itcast.pojo.Ingredient' for property 'ingredients[0]': no matching editors or conversion strategy found]
 * @author: Mr.ZGrey
 * @create: 2020-12-24 10:41
 **/
@Component
public class IngredientByIdConverter implements Converter<String, Ingredient> {

    @Autowired
    private IngredientDao ingredientDao;

    @Override
    public Ingredient convert(String source) {
        return ingredientDao.findOne(source);
    }
}

不添加上面的转换器,即使在第3.2章使用Spring Data JPA持久化数据,提交的taco表单也不会报错,因为tacos.Ingredient已经进行对象到数据库的映射,即使不配置如上的转换器 ,也能成功的提交表单。在这种情况下,spring在遇到要要将String转换成tacos.Ingredient时,会认为这个字符串就是他的主键,会根据这个字符串id查找到该对象,并将其加入List中。

  • 另外converter是一个函数式接口 里面有一个方法 T convert(S source);
    可以将类型为S的转换为T类型
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值