Search code examples
javaspring-bootspring-datamany-to-many

How to do a "findByCategory" in a ManyToMany products schema in Spring JPA Repository class?


I am new to Java Spring Frameworks and I know this title sounds too specific, but the answer to this question is useful for any similar many-to-many schemas. I searched a lot for this answer and found none. Please: read full body before downvote or relate to other questions.

I have the entities Product and Category and they are many-to-many related and generated at run-time.

In my REST application I have three important end-points that uses that schema:

  1. /category to list all categories as a menu;
  2. /products?description= to list products filtered by terms in description field;
  3. /category/{id}/products to list products that are in this category.

I have difficult with this last one, as I was told that I should use the @Query annotation to make a join and a where to get the job done. But I believe Spring JPA engineers could not leave this such common task outside the JPA Way.

The second end-point has this method in its repository:

public Page<Produto> findByDescriptionIgnoreCaseContainingOrderByDescriptionAsc(String description, Pageable pageOptions);

The last end-point I was told it should be like:

@Query("select * from products p left join p.category c where c = ?1")
public List<Produto> findByOrderByDescriptionAsc(Lond idCategory)

Can I perform this search as listByCategory(a way to get only one category) without having to use the @Query annotation? If Yes, How?


Solution

  • if you want to get all product bu categoryId

    List<Product> findByCategoriesIdOrderByDescriptionAsc(long categoryId)
    

    OR if you want to get only one record

    Product findFirstByCategoriesIdOrderByDescriptionAsc(long categoryId)