【发布时间】:2023-04-11 12:28:01
【问题描述】:
如何从OneToMany实体实现搜索?我有Book andCategory` 域模型。
public class Category {
private long id;
private String name;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
private Set<Book> books;
}
public class Book {
private long id;
private String title;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
}
这是我在控制器中的方法:
@GetMapping("/books")
public String findAll(Model model, @RequestParam(value = "category", required = false) String category) {
if (category != null && !category.isEmpty()) {
model.addAttribute("books", bookService.findByCategory(category));
} else {
model.addAttribute("books", bookService.findAll());
}
return "book/findAll";
}
我的服务:
@Override
public Iterable<Book> findByCategory(String category) {
return bookRepository.findByCategory(category);
}
还有我的仓库:
Iterable<Book> findByCategory(String category);
请求/books/?category=Computer,浏览器出现以下错误:
There was an unexpected error (type=Internal Server Error, status=500).
Parameter value [Computer] did not match expected type [io.github.julianjupiter.springbootjpamanytoone.domain.Category (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [Computer] did not match expected type [io.github.julianjupiter.springbootjpamanytoone.domain.Category (n/a)]
谢谢。
【问题讨论】:
-
我觉得上个标题好多了。
标签: java spring-boot spring-data-jpa