gpt4 book ai didi

java - 如何按类别查找书籍?

转载 作者:行者123 更新时间:2023-11-30 01:54:30 24 4
gpt4 key购买 nike

我有三门课:

BookController.java

@Controller
public class BookController {

@Autowired
private BookRepository book_repository;

@Autowired
private CategoryRepository category_repository;

@Autowired
private BookServiceImpl bookServiceImpl;

@RequestMapping(value = "/booklist")
public String bookList(Model model) {
model.addAttribute("books", book_repository.findAll());
return "booklist";
}

@RequestMapping(value = "/findbycategory")
public List<Book> findBookByCategory()..... (need to implement)

}

Book.java

@Entity
public class Book {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String author;
private int year = 1600;
private String isbn;
private double price;

@ManyToOne
@JsonIgnore
@JoinColumn(name = "categoryId")
private Category category;

setters/getters/constructors...
}

类别.java

@Entity
public class Category {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long categoryId;
private String categoryName;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private List<Book> books;
...
}

BookRepository.java

@RepositoryRestResource
public interface BookRepository extends CrudRepository<Book, Long> {

List<Book> findByAuthor(@Param("author") String author);

List<Book> findByTitleLike(String title);
}

我想编写一个方法 findBooksByCategory() ,它按类别返回所有书籍。我在类别和书籍之间有一对多关系。类别是作为单独的实体。我知道如何通过 id (来自 Book.java)来查找书籍,但我不知道当我们有一个类字段作为其他对象的实例时如何表现。

最佳答案

看看Property Expressions

有多种方法可以实现您想要实现的目标。其中一种可能是;

List<Book> findAllByCategory(Category category);

按照@Compass的建议

如果您想更具体,例如通过类别名称,您可以;

List<Book> findAllByCategoryCategoryName(String categoryName);

List<Book> findAllByCategory_CategoryName(String categoryName);

然后有一种 native 方法可以做到这一点[假设表名称和列];

@Query(value="select b.* from book b inner join category c on b.category = c.id where c.name = ?1", nativeQuery=true)
List<Book> customQueryToFindListOfBooks(String categoryName);

关于java - 如何按类别查找书籍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54931588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com