有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Spring JPA Repository类中的多个产品模式中执行“findByCategory”?

我不熟悉Java Spring框架,我知道这个标题听起来太具体了,但是这个问题的答案对于任何类似的多对多模式都很有用。我找了很多这个答案,但一个也没有找到请:在否决投票前阅读全文或与其他问题相关

我有实体ProductCategory,它们与many-to-many相关并在run-time生成

在我的REST应用程序中,有三个重要的end-points使用了该模式:

  1. /category以菜单形式列出所有类别
  2. /products?description=在描述字段中列出按术语过滤的产品
  3. /category/{id}/products以列出属于此类别的产品

我很难理解最后一个问题,因为有人告诉我应该使用@Query注释来制作joinwhere来完成工作。但我相信Spring JPA工程师不能将这项如此普通的任务置于JPA方式之外

第二个端点在其存储库中有此方法:

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

我被告知的最后一个终点应该是:

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

我是否可以作为listByCategory(a way to get only one category)执行此搜索,而不必使用@Query注释?如果是,如何进行


共 (1) 个答案

  1. # 1 楼答案

    如果你想得到所有的产品类别

    List<Product> findByCategoriesIdOrderByDescriptionAsc(long categoryId)
    

    或者 如果你只想得到一张唱片

    Product findFirstByCategoriesIdOrderByDescriptionAsc(long categoryId)