简体   繁体   中英

How to make an optional/nullable property in hibernate-validator?

I found this implementation that basically do what I want.

@ConstraintComposition(OR)
@NotBlank
@Null
@ReportAsSingleViolation
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = {})
public @interface NullOrNotBlank {
    String message() default "{org.hibernate.validator.constraints.NullOrNotBlank.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

and I use it as

@field:NullOrNotBlank
@field:Size(max = 50)
var middleName: String? = null,

I've also tried

@field:NullOrNotBlank
@field:Size(max = 50)
@field:Column(nullable = true)
var middleName: String? = null,

But this composite constraints makes the field in the database (MySQL) not nullable. So what happens is that it's working fine until I save the Entity to the database.

After I embedded the hibernate-validator my tests also failed too.

Why did the nullable column is changed to non-nullable column by hibernate-validator ?

the hibernate-validator will makes the column to non-nullable column, if you declared any non-nullable constraints on the column, for example:

@[ConstraintComposition(OR) NotBlank Null]
//                          ^---- it is a @NotNull constraint

@NotNull
public @interface NotBlank {...}

How to solve this problem?

IF you have seen my tests on github, you maybe found that I used a @Length which is a nullable constraint, then the hibernate-validator doesn't change the original column definition at all, for example:

@[ConstraintComposition(OR)  Length(min = 1)  Null]
//it is a nullable constraint ---^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM