java - 以另一个实体为条件搜索实体

标签 java mysql spring spring-data

我在实体之间有简单的关系:

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

尽管如此,我确信数据库中存储有此类别的产品(我发现它们直接查看 mysql 并使用 findAll 端点)。谁能解释一下这里出了什么问题?

最佳答案

您在以下代码片段中遇到了问题。

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,这将提供一些方便的方法。

关于java - 以另一个实体为条件搜索实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566049/

相关文章:

mysql - 将类型从简单字符串更改为文本后的 Grails - 第 1 行的 'text' 列的数据太长

mysql - 使用随机唯一数字更新 SQL 表

java - Spring Boot Controller 不响应 POST 请求

spring - 为什么我在 tomcat 6 中得到 "HTTP Status 503 - This application is not currently available"?

java - Intent 不适用于将 fragment 移动到 Activity

java - 如何在 JUnit 测试中引导 weld-se

Mysql按功能分组

java - mybatis 3 selectkey inside foreach

java - "-Drun.profiles=.."尝试执行 Spring Boot jar 时不起作用

java - JPA:与确切类型的实体的一对一关系