java—如何在spring boot中定义多个查询参数

wwodge7n  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(435)

我需要获得多个参数,如名字,姓氏,手机等所需的客户信息。
为此,我决定使用queryparams。
如果我定义我的方法如下

@GetMapping("/customers")
    public ResponseEntity<EntityModel<Customer>> findCustomerByFirstName(@RequestParam(required = false) String firstName) {
        System.out.println();
        return service.findCustomerByFirstName(firstName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
    }
//Last-name
@GetMapping("/customers")
    public ResponseEntity<EntityModel<Customer>> findCustomerByLastName(@RequestParam(required = false, name = "lastName") String lastName) {
        return service.findCustomerByLastName(lastName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
    }

Spring给了我以下的例外。

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'customerController' method
com.test.cas.controller.CustomerController#findCustomerByFirstName(String)
to {GET [/api/customers/]}: There is already 'customerController' bean method
com.test.cas.controller.CustomerController#findCustomerByLastName(String) mapped.

任何克服这一问题的建议都将不胜感激。

uoifb46i

uoifb46i1#

只使用一个Map到一个方法并执行类似操作。

@GetMapping("/customers")
    public ResponseEntity<EntityModel<Customer>> findCustomerByFirstNameOrLastname(
@RequestParam(required = false) String firstName, 
@RequestParam(required = false) String lastName) {
        if (StringUtils.hasText(firstName))
            return service.findCustomerByFirstName(firstName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
        if (StringUtils.hasText(lastName))
            return service.findCustomerByLastName(lastName) //
                .map(assembler::toModel) //
                .map(ResponseEntity::ok) //
                .orElse(ResponseEntity.notFound().build());
    }

这可以用jpa标准规范和一个单独的服务层来编写,但仅限于主要思想。

相关问题