【问题标题】:Searching entity by another entity as criteria以另一个实体作为条件搜索实体
【发布时间】:2018-11-30 22:59:06
【问题描述】:

我在实体之间建立了简单的关系:

class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;
    private double calories;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn
    private Category category;
}

class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(unique = true)
    private String name;

    Category(String name) {
        this.name = name;
    }
}

我正在使用以下存储库

interface ProductRepository extends Repository<Product, Long> {
    Product save(Product product);
    Page<Product> findAll(Pageable pageable);
    Page<Product> findByCategory(Pageable pageable, Category category);
    void delete(Product product);
}

像这样在facade中调用

 public Page<ProductDTO> getProductsByCategory(Pageable pageable, String categoryName) {
        return productRepository.findByCategory(pageable, dtoConverter.toCategory(categoryName))
                .map(Product::toDTO);
    }

dtoConverter

Category toCategory(String categoryName) {
        return new Category(categoryName);
    }

最终将我们引向Controller

@GetMapping("/findCategory")
    Page<ProductDTO> getProductsByCategory(Pageable pageable, @RequestParam String categoryName) {
        return productFacade.getProductsByCategory(pageable, categoryName);
    }

我有非常相似的方法来获取和创建新产品,它很有效,但是一旦我尝试按照上面描述的方式按类别查找产品,我就得到了

{
    "timestamp": "2018-11-30T22:57:29.660+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/products/findCategory=fruit"
}

即使我确定有此类产品存储在 db 中(我发现它们直接查看 mysql 并使用 findAll 端点)。谁能解释一下这里出了什么问题?

【问题讨论】:

    标签: java mysql spring spring-data


    【解决方案1】:

    你下面的sn-p有问题。

    Category toCategory(String categoryName) {
        return new Category(categoryName);
    }
    

    您不能只创建一个新对象。您需要返回一个引用数据库表的对象。所以首先你需要从数据库中检索类别对象,然后返回它。

    因此您将创建一个 CategoryRepository :

    public interface CategoryRepository extends Repository<Category,Long> {
        Category findByName(String name);
    }
    

    然后在你的方法中:

    Category toCategory(String categoryName) {
        return categoryRepository.findByName(categoryName);
    }
    

    旁注:您可以扩展 JpaRepository,而不是 Repository,这将提供一些方便的方法。

    【讨论】:

      【解决方案2】:

      由于您的类别名称是唯一的,您可以将存储库方法更改为

      interface ProductRepository extends Repository<Product, Long> {
          Product save(Product product);
          Page<Product> findAll(Pageable pageable);
          Page<Product> findByCategory_Name(Pageable pageable, String categoryName);
          void delete(Product product);
      }
      

      并在您的 getProductsByCategory 方法中使用它

      public Page<ProductDTO> getProductsByCategory(Pageable pageable, String categoryName) 
      {
          return productRepository.findByCategory_Name(pageable, categoryName))
                  .map(Product::toDTO);
      }
      

      【讨论】:

        最近更新 更多