相关文章推荐

[JAVA] No validator could be found for constraint '@Size` on enum type #12472

Open
@tommysitu

Description

Description

If a Swagger spec declares an enum but also specifies a maxLength , running swagger-codegen with useBeanValidation enabled, will tag the enum with @Size constraint. Invoking validation on the generated model will result in this Java error: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Size' validating type

The reason for the failure is that @Size can only be used to enforce validation on String or Collections, so if it's used on an enum type, the jakarta library will panic.

Swagger-codegen version

The issue is observed in version 3.0.62

Swagger declaration file content or URL

My Swagger spec contains this enum declaration:

        Status:
          type: "string"
          maxLength: 10
          description: "status of something"
          enum:
            - "PENDING"
            - "COMPLETED"
Command line used for generation

This command was run on mac using the latest swagger-codegen installed using brew:

swagger-codegen generate -i sample.yaml -l java --additional-properties useBeanValidation=true -o ./build
$ swagger-codegen version
3.0.62
Steps to reproduce
  • Find a swagger spec that contains enum with maxLenghh or add one to any swagger spec.
  • Run the command above to generate JAVA code with bean validation.
  • Invoke the validation on the model containing the enum using Validation.buildDefaultValidatorFactory().getValidator().validate(toValidate);
  • Related issues/PRs
    Suggest a fix/enhancement

    SImple fix: remove maxLength from the enum declaration, or remove @Size manually in the generated model. However it would be good for swagger-codgen to handle this sensibly.

    Perhaps we can update the mustache template to add @Size for non-enum type like this:

    {{#minLength}}{{#maxLength}}{{^isEnum}} @Size(min={{minLength}},max={{maxLength}}){{/isEnum}}{{/maxLength}}{{/minLength}}
    
     
    推荐文章