Spring Boot Constraint fails validating multipartFile fields with the @NotNull rule

119 Views Asked by At

I have a Spring boot 3.1.2 project with a "Document" entity which has a multipartFile field named "documentFile".

Im trying to endpoint-side validating it using Constraint Validators but it seems to fail when requesting (using a form data):

jakarta.validation.ConstraintViolationException: Validation failed for classes [com.mobiledigitalsales.tecnoalert.model.Document] during persist time for groups [jakarta.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='no debe ser nulo', propertyPath=documentFile, rootBeanClass=class com.mobiledigitalsales.tecnoalert.model.Document, messageTemplate='{jakarta.validation.constraints.NotNull.message}'}
]
    at org.hibernate.boot.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:151) ~[hibernate-core-6.2.6.Final.jar:6.2.6.Final]
    at org.hibernate.boot.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:81) ~[hibernate-core-6.2.6.Final.jar:6.2.6.Final]
    at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:215) ~[hibernate-core-6.2.6.Final.jar:6.2.6.Final]

Heres a look of the entity and it controller class:

@Entity
class Document (

    @Id
    @GeneratedValue
    override var id: Long? = null,

    @field:NotNull
    @Transient
    var documentFile: MultipartFile? = null,
    //...

)
@RestController
class DocumentController() {

    @PostMapping("/documents")
    @ResponseStatus(HttpStatus.CREATED)
    fun create(@Valid @ModelAttribute document: Document): Document {
        return _documentService.create(document)
    }

}

I have tried using @Validated instead of @Valid too, but didn't worked, someone suggested to debug it but i haven't a real clue of what to debug/inspect.

Im currently wondering if @field:NotNull actually would works to validate that a MultipartFile field is not null, if not then what would fit better with it?

0

There are 0 best solutions below