简体   繁体   English

如果传入请求的字段少于或多于 POJO,我如何告诉 Hibernate 验证器抛出异常

[英]How can I tell Hibernate Validator to throw exception if the incoming request has less or extra fields than the POJO

For example my POJO has two field例如我的 POJO 有两个字段

public class User {
    @NotNull
    private String firstName;
    @NotNull
    private String lastName;
}

if the incoming request body is like the following, the hibernate won't throw any error, since all required field is there.如果传入的请求正文如下所示,则 hibernate 不会抛出任何错误,因为所有必填字段都在那里。

{
  "firstName": "cat",
  "lastName": "dog",
  "extraField": "whatever"
}

Is there any way I can tell hibernate to check this kind of scenario?有什么办法可以告诉 hibernate 检查这种情况吗? I know I can just @JsonCreator to do the trick.我知道我可以通过@JsonCreator来解决问题。 But is it the good approach to combine both hibernate and Jackson together?但是将 hibernate 和 Jackson 结合在一起是不是一个好方法?

If you are using auto configuration then the following property in application.properties will do the trick.如果您使用自动配置,那么 application.properties 中的以下属性就可以解决问题。

spring.jackson.deserialization.fail-on-unknown-properties=true

This is equivalent to the following这等价于以下

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

I did a small test without spring and it throws an exception com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException我做了一个没有 spring 的小测试,它抛出异常com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Hibernate中将字段添加到POJO? - How to add fields to POJO in Hibernate? spring boot请求体中有额外参数时如何抛出异常 - How to throw exception when there is extra parameters in request body spring boot 使用 Hibernate Validator 在 Spring Boot 中进行 Bean 验证失败时如何抛出自定义异常? - How to Throw a Custom Exception When Bean Validation In Spring Boot with Hibernate Validator Fails? 可以休眠将一个pojo数据转换为几乎没有字段的另一个pojo - Can hibernate convert one pojo data into the another pojo with few fields 我所有的字段都有一个前缀。 我该如何告诉它休眠? - All my fields have a prefix. How can I tell that to hibernate? 如何在Spring中添加错误以请求上下文而不是引发异常 - How to add an error to request context rather than throw exception in Spring 如何使用休眠Pojo文件重新创建数据库 - How can I recreate my database with hibernate pojo files 如何判断当前tx(Hibernate)中是否删除了Grails / GORM域实例? - How can I tell if a Grails/GORM domain instance has been deleted in the current tx (Hibernate)? 更改字段后,如何在Hibernate中引发异常? - How do I throw an exception with Hibernate when a field is changed? 是否存在可以使用类字段的此类约束(休眠验证程序)? - Is there such constraints (Hibernate Validator) that can use class fields?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM