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 {
.
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!"));
}
}
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);
}
}