【问题标题】:Get Method with Params returning null always获取参数的方法总是返回 null
【发布时间】:2021-09-02 16:55:05
【问题描述】:

我正在尝试使用 @GetMapping 进行搜索查询 使用 JPA 和 SpringBoot

这里是控制器使用的方法:

    @GetMapping("/search{min_price}{max_price}{text}")
    public Optional<Product> searchProducts(@PathVariable(required = false) Integer min_price,
                                            @PathVariable(required = false) Integer max_price,
                                            @PathVariable(required = false) String text
    ) {
        Optional<Product> products = productRepository.SearchProduct(min_price, max_price, text);
        return products;
    }

这里是我在存储库中创建的@Query:(我将@Param 名称更改为 ?X 并且问题仍然存在)

    @Query("SELECT P FROM Product P " +
            "where (P.name like CONCAT('%',lower(?3),'%') or P.description like CONCAT('%',lower(?3),'%')) " +
            "and (?2 is null or P.price <= ?2) " +
            "and (?1 is null or P.price >= ?1)")
    Optional<Product> SearchProduct(@Param("max_price") Integer min_price,
                                    @Param("min_price") Integer max_price,
                                    @Param("text") String text);

我是第一次使用 H2 数据库,不知道 ?X 是否是使用其中变量的正确方法。 (在 PL-SQL 中,我使用 :X 来实现此目的)。

当我得到一个 get 时,Postman 中的返回总是“null”

这是我所做的获取示例“search?min_price=1&max_price=200&text=prod” 该数据库有 5 个条目,如果我直接在 DB 2 中使用此值进行搜索,结果符合条件。

【问题讨论】:

    标签: java spring jpa h2


    【解决方案1】:

    通过/分隔路径参数

    @GetMapping("/search/{min_price}/{max_price}/{text}")
    

    并更新您的客户端请求以匹配,或改用@RequestParam

    public Optional<Product> searchProducts(@RequestParam Integer min_price,
                        @RequestParam Integer max_price,
                        @RequestParam String text)
    

    【讨论】:

    • 如果我使用 / 来分隔我需要在获取 URL 时使用这个 / 对吗?然后我需要为此使用 RequestParam。但是关于在 H2 中引用变量的方式,是否正确使用 ?1、?2、?3 来引用它们,尊重函数中给出的顺序?实际上,我认为它有效:查询没有返回唯一结果:2 现在我只需要检查一下。谢谢
    • 这两个选项是互斥的。您当前的 URL 模式需要 @RequestParam 才能读取参数。如果你想使用@PathVariable,那么你需要使用类似/search/1/200/prod
    • 我可以在这里解决所有问题。你的小费救了我哈哈,非常感谢。
    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2020-08-16
    • 2022-10-21
    • 2016-07-10
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多