我正在通过“Spring in action 5”学习 Spring 并遇到一些问题:当我在第 3 章中从 JDBC 切换到 Spring Data JPA(100% 正常工作)时,代码停止工作,因为我尝试打开主页塔可的成分。我做了一些日志来查看发生了什么,发现方法 findById(String id) 无法从 DB(或类似的东西)转换我的值。我正在使用 MySQL。
我尝试使用@Autowired 自己调用转换器的方法 convert(String id),但我发现的唯一一件事是当键错误时,会出现另一个错误。所以数据是可见的。我会尝试在这里提供一些代码,但我不确定什么有用,什么没用。我在第一次尝试记录某些东西时出错。IDE 和浏览器中的错误是不同的。这是完整的项目https://github.com/thedistantblue/taco-cloud-jpa。
这是我的转换器:
public class IngredientByIdConverter implements Converter<String,
Ingredient> {
private IngredientRepository ingredientRepo;
@Autowired
public IngredientByIdConverter(IngredientRepository ingredientRepo) {
this.ingredientRepo = ingredientRepo;
}
@Override
public Ingredient convert(String id) {
log.info("In converter.convert(): "
+ingredientRepo.findById(id).toString());
Optional<Ingredient> optionalIngredient =
ingredientRepo.findById(id);
return optionalIngredient.orElse(null);
}
}
Run Code Online (Sandbox Code Playgroud)
和控制器类:
@Slf4j
@Controller
@RequestMapping("/design")
@SessionAttributes("order")
public class DesignTacoController {
@ModelAttribute(name = "order")
public Order order() { …Run Code Online (Sandbox Code Playgroud)