thymeleaf Failed to convert property value of type java.lang.String to required type java.util.List

前端 未结 2 649
误落风尘
误落风尘 2020-12-20 07:57

I am new to Spring and Spring Boot and am working through a book that is full of missing information.

I have a taco class:

public class Taco {

    .         


        
相关标签:
2条回答
  • 2020-12-20 08:25

    An optimisation of Ian's answer above:

    Fetch the ingredients in the constructor of the converter.

    package com.joeseff.xlabs.chtp01_1.tacos.converter;
    
    import com.joeseff.xlabs.chtp01_1.tacos.model.Ingredient;
    import com.joeseff.xlabs.chtp01_1.tacos.respository.jdbc.IngredientRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.core.convert.converter.Converter;
    import org.springframework.stereotype.Component;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author - JoeSeff
     * @created - 23/09/2020 13:41
     */
    @Component
    public class IngredientConverter implements Converter<String, Ingredient> {
        private final IngredientRepository ingredientRepo;
        private final List<Ingredient> ingredients = new ArrayList<>();
        
        @Autowired
        public IngredientConverter(IngredientRepository ingredientRepo) {
            this.ingredientRepo = ingredientRepo;
        
            ingredientRepo.findAll().forEach(ingredients::add);
        }
        
        @Override
        public Ingredient convert(String ingredientId) {
            return ingredients
                    .stream().filter( i -> i.getId().equals(ingredientId))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("Ingredient with ID '" + ingredientId + "' not found!"));
        }
    }
    
    0 讨论(0)
  • 2020-12-20 08:30

    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);
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题