OpenAPITools / OpenAPITools/openapi-generator

[BUG] [java] [resttemplate] Model fields not propertly initialized (won't compile) when using generateAliasAsModel

Open
#8,156 3 comments 0 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

Description

When generating client code with openapi-generator and the generateAliasAsModel option set to true, standard model
fields of alias object types are initialized to a new instance of the base object type, not the alias object type, and compilation fails with an incompatible type error.

For example:

public class StandardModelClass {
  private MapAliasModelClass mapAliasModel = new HashMap<String, String>();
}
openapi-generator version

Using 4.3.1, but issue also exists in latest 5.0.0-SNAPSHOT.

OpenAPI declaration file content or url

Example swagger contract.

Generation Details

The code is being generated using the Maven plugin. See example project.

Steps to reproduce

See example project README.

Related issues/PRs

This appears to be the same issue as #3602. I didn't dig into the code that was merged for that issue, so I'm not sure if that code only fixed a specific instance/scenario or if this is a regression issue.

Suggest a fix

Is there a reason that the model fields can't be initialized to null instead of a new instance? The implementation could be greatly simplified by modifying the pojo.mustache template to initialize the fields to null. However, I am hesitant to create a pull request with that change without knowing the reason that the fields are currently being initialized the way they are. Also, simplifying the implementation like that could result in unnecessary code in the codebase that might be better cleaned up by someone more familiar with all of the moving parts.

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 linked swagger.json and example project's README, reproduce generation through the Maven plugin, and inspect the generated model field initialization. Read pojo.mustache and compare the generated alias field type with its initializer; use the compilation result to confirm the issue is resolved and consider coverage for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, openapi
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.