zoukankan      html  css  js  c++  java
  • 【spring实战第五版遇到的坑】3.1中的例子报错 coder

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

  • 相关阅读:
    simian 查找项目中的重复代码
    idea 启动 ShardingProxy
    kafka 加密通信,python-kafka 访问加密服务器
    apt-get 修改源
    短轮询、长轮询、SSE 和 WebSocket
    前端模块化:CommonJS,AMD,CMD,ES6
    Set、Weak Set、Map、Weak Map学习笔记
    博客园应该如何运营
    Vue中Route的对象参数和常用props传参
    Dapper的新实践,Dapper.Contrib的使用与扩展
  • 原文地址:https://www.cnblogs.com/coder-qi/p/10706765.html
Copyright © 2011-2022 走看看