Skip to content

[Java] Fix issue 22209 oneof pojo #23594

Open
Chhida wants to merge 3 commits intoOpenAPITools:masterfrom
Chhida:fix-issue-22209-oneof-pojo
Open

[Java] Fix issue 22209 oneof pojo #23594
Chhida wants to merge 3 commits intoOpenAPITools:masterfrom
Chhida:fix-issue-22209-oneof-pojo

Conversation

@Chhida
Copy link
Copy Markdown
Contributor

@Chhida Chhida commented Apr 21, 2026

fixes #22209

  • Add useOneOfPojo option to generate real POJO classes for oneOf schemas instead of wrapper models

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

Summary by cubic

Adds a useOneOfPojo option to Java generators to emit real POJO classes for oneOf schemas instead of abstract wrapper models, fixing oneOf inheritance and serialization issues. Fixes #22209. Adds a Jersey3 sample and config to demonstrate the option.

  • New Features

    • New additional-property useOneOfPojo (default: false).
    • When enabled, oneOf models are generated as concrete POJOs; wrapper model is not created.
    • Overrides updateModelForComposedSchema() to skip merging for oneOf and restore original vars; option handled in processOpts(); CLI option added; docs updated across Java generators.
    • Added bin/configs/java-jersey3-oneOf-pojo.yaml and samples/client/petstore/java/jersey3-oneOf-pojo/ to validate output.
  • Migration

    • Opt-in by passing --additional-properties useOneOfPojo=true (or set in config). No breaking changes by default.

Written for commit 7830618. Summary will update on new commits.

… of abstract wrapper and ensure real POJO model is produced

- Add useOneOfPojo option to generate real POJO classes for oneOf schemas instead of wrapper models
- Override updateModelForComposedSchema() to restore original vars when option is enabled
- Process the option in processOpts() method with default value false for backward compatibility

fixes OpenAPITools#22209
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 118 files

Note: This PR contains a large number of files. cubic only reviews up to 75 files per PR, so some files may not have been reviewed. cubic prioritises the most important files to review.

@Chhida Chhida force-pushed the fix-issue-22209-oneof-pojo branch from 0d98002 to 09ed65d Compare April 21, 2026 10:50
- Added bin/configs/java-jersey3-oneOf-pojo.yaml config with useOneOfPojo: true
- Generated samples/client/petstore/java/jersey3-oneOf-pojo/
- Demonstrates how useOneOfPojo=true generates real POJO classes instead of wrapper models
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7 issues found across 47 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="samples/client/petstore/java/jersey3-oneOf-pojo/src/main/java/org/openapitools/client/Configuration.java">

<violation number="1" location="samples/client/petstore/java/jersey3-oneOf-pojo/src/main/java/org/openapitools/client/Configuration.java:39">
P2: `AtomicReference.updateAndGet` callback invokes a potentially side-effectful supplier, which may run multiple times under contention.</violation>
</file>

<file name="samples/client/petstore/java/jersey3-oneOf-pojo/README.md">

<violation number="1" location="samples/client/petstore/java/jersey3-oneOf-pojo/README.md:18">
P2: README minimum Java version is incorrect for the Jersey 3.1 dependency baseline.</violation>
</file>

<file name="samples/client/petstore/java/jersey3-oneOf-pojo/src/main/java/org/openapitools/client/RFC3339JavaTimeModule.java">

<violation number="1" location="samples/client/petstore/java/jersey3-oneOf-pojo/src/main/java/org/openapitools/client/RFC3339JavaTimeModule.java:32">
P2: Custom deserializers are registered after `super.setupModule(context)`, so they may not be applied to the mapper during module registration.</violation>
</file>

<file name="samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh">

<violation number="1" location="samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh:42">
P2: The script checks for any remote instead of specifically checking for `origin`, which can cause pull/push failures when only non-`origin` remotes exist.</violation>

<violation number="2" location="samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh:48">
P2: Access token is embedded in the Git remote URL, risking plaintext secret exposure in `.git/config` and related tooling.</violation>

<violation number="3" location="samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh:57">
P2: `git push` failures can be masked because the script returns the pipeline/`grep` status instead of the push command status.</violation>
</file>

<file name="samples/client/petstore/java/jersey3-oneOf-pojo/src/main/java/org/openapitools/client/ApiClient.java">

<violation number="1" location="samples/client/petstore/java/jersey3-oneOf-pojo/src/main/java/org/openapitools/client/ApiClient.java:851">
P2: Form-urlencoded serialization overwrites accumulated parameters, causing only the last field to be sent.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread samples/client/petstore/java/jersey3-oneOf-pojo/README.md
Comment thread samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh
Comment thread samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh
Comment thread samples/client/petstore/java/jersey3-oneOf-pojo/git_push.sh
@jpfinne
Copy link
Copy Markdown
Contributor

jpfinne commented Apr 21, 2026

@Chhida I don't think the generated code will work.
For example, how to use SchemaA in public ApiResponse<Void> rootPostWithHttpInfo(@jakarta.annotation.Nullable PostRequest postRequest) throws ApiException ?

The inline oneOf complexifies the generation. This is simpler:

components:
  schemas:
    schemaA:
      properties:
        propA:
          type: string
      type: object
    __post_request:
      oneOf:
        - $ref: "#/components/schemas/schemaA"
        - $ref: "#/components/schemas/SchemaAdditional"
    SchemaAdditional:
      additionalProperties: true
      properties: {}
      type: object

The spring generator has an option USE_DEDUCTION_FOR_ONE_OF_INTERFACES

For example:

generateFromContract(
      "src/test/resources/3_0/spring/issue_22209.yaml", SPRING_BOOT,
      Map.of(USE_DEDUCTION_FOR_ONE_OF_INTERFACES, true,
              USE_ONE_OF_INTERFACES, true,
              GENERATE_ALIAS_AS_MODEL, true));

It generates:

@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
    @JsonSubTypes.Type(value = SchemaA.class), 
    @JsonSubTypes.Type(value = SchemaAdditional.class)
})
public interface PostRequest {
}

I would implement USE_DEDUCTION_FOR_ONE_OF_INTERFACES for the java generators:

  • move USE_DEDUCTION_FOR_ONE_OF_INTERFACES to AbstractJavaCodegen
  • add the logic in modules/openapi-generator/src/main/resources/Java/oneof_interface.mustache. See modules/openapi-generator/src/main/resources/JavaSpring/oneof_interface.mustache

@Chhida
Copy link
Copy Markdown
Contributor Author

Chhida commented Apr 22, 2026

@Chhida I don't think the generated code will work. For example, how to use SchemaA in public ApiResponse<Void> rootPostWithHttpInfo(@jakarta.annotation.Nullable PostRequest postRequest) throws ApiException ?

The inline oneOf complexifies the generation. This is simpler:

components:
  schemas:
    schemaA:
      properties:
        propA:
          type: string
      type: object
    __post_request:
      oneOf:
        - $ref: "#/components/schemas/schemaA"
        - $ref: "#/components/schemas/SchemaAdditional"
    SchemaAdditional:
      additionalProperties: true
      properties: {}
      type: object

The spring generator has an option USE_DEDUCTION_FOR_ONE_OF_INTERFACES

For example:

generateFromContract(
      "src/test/resources/3_0/spring/issue_22209.yaml", SPRING_BOOT,
      Map.of(USE_DEDUCTION_FOR_ONE_OF_INTERFACES, true,
              USE_ONE_OF_INTERFACES, true,
              GENERATE_ALIAS_AS_MODEL, true));

It generates:

@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
    @JsonSubTypes.Type(value = SchemaA.class), 
    @JsonSubTypes.Type(value = SchemaAdditional.class)
})
public interface PostRequest {
}

I would implement USE_DEDUCTION_FOR_ONE_OF_INTERFACES for the java generators:

  • move USE_DEDUCTION_FOR_ONE_OF_INTERFACES to AbstractJavaCodegen
  • add the logic in modules/openapi-generator/src/main/resources/Java/oneof_interface.mustache. See modules/openapi-generator/src/main/resources/JavaSpring/oneof_interface.mustache

*@jpfinne - Thank you for your suggestion. Here's my analysis:

Test with our Schema in the issue #22209

I tested useDeductionForOneOfInterfaces with our Spring generator using our schema. The schema has a discriminator:

"SimulationDto": {
  "discriminator": {
    "propertyName": "type"
  },
  "oneOf": [
    { "$ref": "#/components/schemas/SimulationSatdDto" },
    { "$ref": "#/components/schemas/SimulationMedDto" },
    { "$ref": "#/components/schemas/SimulationPcaDto" }
  ]
}

Result with useDeductionForOneOfInterfaces=true

Even with this option enabled, the schema has a discriminator, so the template generates @JsonTypeInfo.Id.NAME (not DEDUCTION):

// SimulationDto.java (generated in output-spring-deduction/src/main/java/org/openapitools/model/)
package org.openapitools.model;

@JsonIgnoreProperties(
  value = "type",
  allowSetters = true
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SimulationMedDto.class, name = "SimulationMedDto"),
  @JsonSubTypes.Type(value = SimulationPcaDto.class, name = "SimulationPcaDto"),
  @JsonSubTypes.Type(value = SimulationSatdDto.class, name = "SimulationSatdDto")
})
public interface SimulationDto {
    public String getType();  // Only method, no property getters/setters!
}

Problem: Parent is Interface, Not Class

Spring generates SimulationDto as an interface, not a class. The interface only has getType() method - no property getters/setters.

Generated Java Client with useOneOfPojo=true

With this PR useOneOfPojo=true, the generated Java client code correctly preserves parent properties:

@JsonIgnoreProperties(
  value = "type",
  allowSetters = true
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SimulationMedDto.class, name = "SimulationMedDto"),
  @JsonSubTypes.Type(value = SimulationPcaDto.class, name = "SimulationPcaDto"),
  @JsonSubTypes.Type(value = SimulationSatdDto.class, name = "SimulationSatdDto"),
})
public class SimulationDto {
  public static final String JSON_PROPERTY_CODIQUE = "codique";
  @jakarta.annotation.Nullable
  private String codique;

  public static final String JSON_PROPERTY_HORODATAGE_SIMULATION = "horodatageSimulation";
  @jakarta.annotation.Nullable
  private LocalDateTime horodatageSimulation;

  public static final String JSON_PROPERTY_HORODATAGE_LANCEMENT_POURSUITE = "horodatageLancementPoursuite";
  @jakarta.annotation.Nullable
  private LocalDateTime horodatageLancementPoursuite;

  public enum StatutPoursuiteEnum {
    A_DEMANDER("A_DEMANDER"),
    DEMANDEE("DEMANDEE"),
    A_CREER("A_CREER"),
    CREEE("CREEE"),
    ERREUR("ERREUR");
    // ... enum methods
  }

  public static final String JSON_PROPERTY_STATUT_POURSUITE = "statutPoursuite";
  @jakarta.annotation.Nullable
  private StatutPoursuiteEnum statutPoursuite;
  // ... getters and setters
}

This solves issue #22209 - parent properties are now correctly generated in the POJO class and polymorphism works as expected

@jpfinne
Copy link
Copy Markdown
Contributor

jpfinne commented Apr 22, 2026

@Chhida Your new sample is totally different. USE_DEDUCTION_FOR_ONE_OF_INTERFACES is used when there is NO discriminator (as in your first sample).

I think my PR #23543 solves your issue. It introduces a new REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING normalizer so available for all generators.

I don't find the contract in #22209 so I can't test it. Can you?

@Chhida
Copy link
Copy Markdown
Contributor Author

Chhida commented Apr 22, 2026

@Chhida Your new sample is totally different. USE_DEDUCTION_FOR_ONE_OF_INTERFACES is used when there is NO discriminator (as in your first sample).

I think my PR #23543 solves your issue. It introduces a new REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING normalizer so available for all generators.

I don't find the contract in #22209 so I can't test it. Can you?
@jpfinne , this is my json schema
simulations.json

@jpfinne
Copy link
Copy Markdown
Contributor

jpfinne commented Apr 22, 2026

@Chhida using the REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING, I get

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SimulationMedDto.class, name = "SimulationMedDto"),
  @JsonSubTypes.Type(value = SimulationPcaDto.class, name = "SimulationPcaDto"),
  @JsonSubTypes.Type(value = SimulationSatdDto.class, name = "SimulationSatdDto")
})

public class SimulationDto {
  // all the fields of SimulationDto + getters/setters
}
public class SimulationPcaDto extends SimulationDto {

But... the contract should be simplified first.
statusPoursuite is defined several times as inline enums or as simple strings. Avoid inlining and use $ref to #/component/schemas/statusPoursuite No need to generate inner classes like RechercherResultatSimulationMedAvecNombresDto.StatutPoursuiteEnum

SimulationPcaDto' extends SimulationDto` AND redefines 'horodatageSimulation', 'statusPoursuite'... That will create random generation issues depending on the options choosen (composition, inheritance..)

@Chhida
Copy link
Copy Markdown
Contributor Author

Chhida commented Apr 22, 2026

@Chhida using the REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING, I get

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SimulationMedDto.class, name = "SimulationMedDto"),
  @JsonSubTypes.Type(value = SimulationPcaDto.class, name = "SimulationPcaDto"),
  @JsonSubTypes.Type(value = SimulationSatdDto.class, name = "SimulationSatdDto")
})

public class SimulationDto {
  // all the fields of SimulationDto + getters/setters
}
public class SimulationPcaDto extends SimulationDto {

But... the contract should be simplified first. statusPoursuite is defined several times as inline enums or as simple strings. Avoid inlining and use $ref to #/component/schemas/statusPoursuite No need to generate inner classes like RechercherResultatSimulationMedAvecNombresDto.StatutPoursuiteEnum

SimulationPcaDto' extends SimulationDto` AND redefines 'horodatageSimulation', 'statusPoursuite'... That will create random generation issues depending on the options choosen (composition, inheritance..)

[@jpfinne] - Thank you for your analysis.

You're correct that our schema has structural issues (inline enums, property redefinitions). However, we have a constraint to not modify the schema as it's a production API contract.

this PR (useOneOfPojo=true) solves our use case:

  • Works with our existing schema
  • Parent properties (codique, horodatageSimulation, etc.) are correctly generated
  • Generated code compiles and polymorphism works as expected

@Mattias-Sehlstedt
Copy link
Copy Markdown
Contributor

Note: I am only a contributor, so everything is my own opinions.

Hi, could we updated the issue with details regarding what exactly that we are generating and with what settings, so it is possible to reason around what is possible for your scenario? I would assume it is a java client with useOneOfInterfaces?

Could we also extend the generated samples (i.e., the tests) to be something more complex/representative? Currently it does not give a good intuition of what we are trying to achieve, as highlighted also by questions asked previously as well.

What is the reason for the interface being insufficient due to lacking getters/setters? If it is the fact that we cannot act on the inteface reference when we pass it around (e.g., shared value X is not present), then would it not be somewhat solved with useSealedOneOfInterfaces, since then we could easily just do a switch when we actually want to act upon the data from one of the implementing classes?

I would also like to state that I am generally against this change. The generator already have a lot of discriminator settings, that all cover one of the odd cases of possible ways to express polymorphism in OAS. The generator should not own the "corner-case fixes" for these scenarios. And if you consider a scenario to not be a corner case. Then please showcase this with sources and tests that illustrate that this is a meaningful general behavior.

Being able to inject a Normalizer is a gift from heaven (from @jpfinne), and I believe it should always be the preferred approach, since client's should own their own corner-cases on their end and not bloat this project with those configurations. This will act as a better mechanism for guiding all using OAS to get a joint understanding of how to best express polymorphism for Java.

@jpfinne
Copy link
Copy Markdown
Contributor

jpfinne commented Apr 25, 2026

@Mattias-Sehlstedt @Chhida my PR #23543 takes the approach of an OpenApiNormalizer rule.
It now works for simulations.json

for example:

generateFromContract(
      "src/test/resources/3_0/spring/issue_22209.yaml", SPRING_BOOT, Map.of(),
      codegen -> codegen.addOpenapiNormalizer("REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING", "true")
                         .addInlineSchemaOption("RESOLVE_INLINE_ENUMS", "true"));

The normalizer removes the oneOf:

    SimulationDto:
      required:
      - type
      type: object
      properties:
        codique:
          type: string
          description: Code codique
        horodatageSimulation:
          type: string
          description: Date à laquelle est réalisée la simulation
          format: date-time
        horodatageLancementPoursuite:
          type: string
          description: Date à laquelle les dernières poursuites ont été lancées
          format: date-time
        statutPoursuite:
          type: string
          description: Statut de la poursuite
          enum:
          - A_DEMANDER
          - DEMANDEE
          - A_CREER
          - CREEE
          - ERREUR
        type:
          type: string
      description: Représente une simulation pour l'application NARA
      discriminator:
        propertyName: type
        mapping:
          SimulationMedDto: "#/components/schemas/SimulationMedDto"
          SimulationPcaDto: "#/components/schemas/SimulationPcaDto"
          SimulationSatdDto: "#/components/schemas/SimulationSatdDto"

There was a bug in InlineModelResolver, the enum in the SimulationDto was not converted.
Now the InlineModelResolver converts the inline statutPoursuite into:

statutPoursuite:
     $ref: "#/components/schemas/RechercherResultatSimulationMedAvecNombresDto_statutPoursuite"

The generator detects inheritance and generates a normal class:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SimulationMedDto.class, name = "SimulationMedDto"),
  @JsonSubTypes.Type(value = SimulationPcaDto.class, name = "SimulationPcaDto"),
  @JsonSubTypes.Type(value = SimulationSatdDto.class, name = "SimulationSatdDto")
})
public class SimulationDto {

  private @Nullable String codique;

  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
  private @Nullable OffsetDateTime horodatageSimulation;

  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
  private @Nullable OffsetDateTime horodatageLancementPoursuite;

  private @Nullable RechercherResultatSimulationMedAvecNombresDtoStatutPoursuite statutPoursuite;
 
  private String type;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix issue 22209: [JAVA-gen] Fix oneOf inheritance: prevent generation of abstract wrapper and ensure real POJO model is produced

3 participants