Skip to content

[BUG][JAVA][SpringCodegen] Inheritance copyOf() results in null parent attributes #19425

@marvinsommer

Description

@marvinsommer
Description

Using inheritance via the normalizer setting

REF_AS_PARENT_IN_ALLOF

together with Builder generation, yields the following code for toBuilder methods

public Dog.Builder toBuilder() {
    Dog.Builder builder = new Dog.Builder();
    return builder.copyOf(this);
}

copyOf looks like this

protected Builder copyOf(Dog value) { 
    super.copyOf(instance);
    this.instance.setIsGoodBoy(value.isGoodBoy);
    return this;
}

Since super.copyOf(instance) is called instead of super.copyOf(value) we loose all set parent model values. instance is a fresh object without set values since the constructor was called in the .toBuilder() call.

public Builder() {
    this(new Dog());
}

protected Builder(Dog instance) {
    super(instance); // the parent builder shares the same instance
    this.instance = instance;
}

Instead the copyOf method should look like this to retain all parent model values:

protected Builder copyOf(Dog value) { 
    super.copyOf(value);
    this.instance.setIsGoodBoy(value.isGoodBoy);
    return this;
}
openapi-generator version

@generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2024-08-22T10:43:42.285171+02:00[Europe/Berlin]", comments = "Generator version: 7.7.0")

Issue still persists in 7.8.0, since related .mustache file is still the same.

modules/openapi-generator/src/main/resources/JavaSpring/javaBuilder.mustache

Generated file example:
Dog.java

OpenAPI declaration file content or url

Dog.yml

Generation Details

Builder Pattern generation enabled

Normalizer settings:
REF_AS_PARENT_IN_ALLOF

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions