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.