OpenAPITools / OpenAPITools/openapi-generator

[BUG][Java][Spring] Bean validation annotates required nullable fields with @NotNull

Open
#21,050 0 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Bug Report Checklist
  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

The java bean validation annotates properties that are required but where the field is potentially null with the @NotNull annotation. This seems to be only the case when the field is not marked as readOnly.

For example the following schema

foo:
 required:
   - bar
  properties:
   bar:
     type: [number, "null"]

allows that the user provides

{"bar": null}

but the generated bean validation will reject it.

openapi-generator version

Tried it with both 7.12 and master (7a3ea28).

OpenAPI declaration file content or url
openapi: 3.1.1
info:
  title: Stripped petstore
  version: 1.0
paths:
  /pet:
    put:
      operationId: updatePet
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Pet'
        required: true
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pet'
components:
  schemas:
    Pet:
      required:
        - name
      type: object
      properties:
        name:
          type: [string, "null"]
          examples: [doggie]

Note: this is a 3.1 openapi, but this can probably easily be translated to a previous version.

Generation Details

Stripped version of the jersey3 config, but probably works with any beanValidation enabled java.

generatorName: jaxrs-jersey
outputDir: samples/server/petstore/jaxrs/jersey3
library: jersey3
additionalProperties:
  artifactId: jaxrs-jersey3-petstore-server
  hideGenerationTimestamp: "true"
  serverPort: "8082"
Steps to reproduce

Generate code with the given spec and config, observe the following model is generated

public class Pet   {
  public static final String JSON_PROPERTY_NAME = "name";
  @JsonProperty(JSON_PROPERTY_NAME)
  private String name;

....

  /**
   * Get name
   * @return name
   **/
  @JsonProperty(value = "name")
  @Schema(required = true, description = "")
  @NotNull 
  public String getName() {
    return name;
  }
....
}

Note the @NotNull on getName(), eventhough that null is explicitly marked as a valid value for the name property. I would expect that this is absent if null is a valid value for the property.

Adding verbose output I see in the ModelInfo for "name"

{ 
  "isString" : true,
   ...
   "isReadOnly" : false,
   "isWriteOnly" : false,
    "isNullable" : true,
}

so internally it correctly picks up the null-ability of the field.

Related issues/PRs

This issue was already partially discussed in #14765, but there it was stated that it is a separate point warranting a separate issue. I could not find such issue.

Suggest a fix

It looks like the 'beanValidation.mustache' is the source, where it says:
{{#required}}{{^isReadOnly}}@NotNull {{/isReadOnly}}{{/required}}
changing it to
{{#required}}{{^isReadOnly}}{{^isNullable}}@NotNull {{/isNullable}}{{/isReadOnly}}{{/required}}
fixes it, but I can't oversee if this has side effects.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the beanValidation.mustache template and the ModelInfo fields shown in the report, then reproduce the issue with the provided Pet schema and jaxrs-jersey3 configuration. Done means generated Java bean validation accepts required properties whose OpenAPI type explicitly permits null, while retaining validation for non-nullable required properties and the existing readOnly behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, openapi
Domain
api, tooling
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.