How to find a book by category?

I have three classes:

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...
}

Category.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);
}

I want to write a method findBooksByCategory() which returns all books by category. I have OneToMany relationship between Category and Book. Category is as separate entity. I would know how to find book by lets say id (from Book.java) but I don't know how to behave when we have a class field as an instance of other object.

Upvotes: 1

Views: 911

Answers (1)

SSC
SSC

Reputation: 3008

Have a look at Property Expressions

There are multiple ways to achieve what you are trying to achieve. One of the possible ones will be;

List<Book> findAllByCategory(Category category);

as suggested by @Compass

If you want to be more specific e.g. by category name, you can;

List<Book> findAllByCategoryCategoryName(String categoryName);

or

List<Book> findAllByCategory_CategoryName(String categoryName);

and then there is a native way to do this [assuming table names & columns];

@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);

Upvotes: 2

Related Questions