RestController Spring Boot 2.7中的错误请求

xxb16uws  于 2023-01-13  发布在  Spring
关注(0)|答案(2)|浏览(202)

我检查了几种不同的方式来检查哪里是错误,但我仍然不知道答案。
这是我的RestController

@RestController
public class CustomerController {
    @PostMapping(value = "/customer")
    public ResponseEntity<CustomerResponse> addCustomer(@RequestBody @Valid Customer custRequest) throws Exception {
        ModelMapper modelMapper = new ModelMapper();
        CustomerDto customerDto = modelMapper.map(custRequest, CustomerDto.class);
        CustomerDto addCust = customer.addCustomer(customerDto);
        CustomerResponse custResponse = modelMapper.map(addCust, CustomerResponse.class);
        return new ResponseEntity<CustomerResponse>(custResponse, HttpStatus.CREATED);
    }
}

那是我的模特

@Entity
@Table(name = "customers")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String idCustomer;
    private String email;
    @OneToMany(mappedBy = "customer",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private List<Choice> choices;
    // Getter and setter and constructor
}

Maven依赖关系

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>

Postman

回应
我怎样才能解决这个问题来发布一个新的客户。

31moq8wy

31moq8wy1#

@Valid允许框架在方法调用时检查参数,如果验证失败,则抛出HTTP 400 Bad Request状态。您有一个复杂类型,该类型也需要验证。下面是一个链接:https://medium.com/javarevisited/are-you-using-valid-and-validated-annotations-wrong-b4a35ac1bca4
试着删除@Valid来看看区别,上面的文章给出了一个示例实现。
此外,使用实体作为请求对象是非常不可取的范例。建议您首先创建特定于请求的DTO对象。在某些情况下,您必须继承,但本问题的范围不是这个。

mitkmikd

mitkmikd2#

Customer的验证似乎失败了。
1.查看日志中的错误详细信息
1.请考虑为请求对象创建一个单独的类。2你并不真的想混合数据库相关的和请求相关的关注点。

相关问题