Spring 数据 JDBC: 找不到 属性 类型

Spring Data JDBC: No such property found for type

我是 Spring 数据 JDBC 的初学者。我正在关注第 6 版中的 Spring 并创建了如下存储库:

package com.springinaction.tacocloud;

import java.util.Optional;

import org.springframework.data.repository.CrudRepository;

public interface IngredientRepository extends CrudRepository<Ingredient, String>{

    public Optional<Ingredient> getById(String id);
    
    public Iterable<Ingredient> getIngredients();
    
    public Ingredient save(Ingredient ingredient);
}

并且我已将此存储库注入到我的控制器中。

@Slf4j
@Controller
@RequestMapping("/design")
public class DesignTacoController {
    
    protected IngredientRepository ingredientRepo;
    
    public DesignTacoController(IngredientRepository ingredientRepo) {
        this.ingredientRepo = ingredientRepo;
    }

    @ModelAttribute
    public void addIngredientsToModel(Model model) {
        Iterable<Ingredient> ingredientsFromJdbc = ingredientRepo.getIngredients();
        //converting Iterable returned by JdbcTemplate to a List
        List<Ingredient> ingredients = new ArrayList<Ingredient>();
        ingredientsFromJdbc.forEach(ingredients::add);
        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(),filterByType(ingredients, type));
        }
    }
.......................................................................

在控制器中调用方法 getIngredients() 会抛出以下异常

nested exception is org.springframework.data.mapping.PropertyReferenceException: No property 'getIngredients' found for type 'Ingredient'!

我在这里错过了什么?

把方法getIngredients()去掉,改用findAll()(超级接口提供)

你也应该去掉其他的方法,因为它们已经被超级接口提供了

  • save() <- 由 CrudRepository
  • 提供
  • getById() <- CrudRepository 提供 Optional<T> findById(ID id);
  • getIngredients <- CrudRepository 提供 Iterable<T> findAll();